java sending mail automatically - java

I wanted the mail to be sent automatically at a specific time. I am able to send a mail but I can't make it to be done automatically . Can anyone please tell me how to send automatically? These below are my codes for sending a mail:
public class SendEmail {
String d_email = "sofien.fkih#gmail.com",
d_password = "",
d_host = "smtp.gmail.com",
d_port = "465",
m_to = "sofien.fkih#gmail.com",
m_subject = "Testing",
m_text = "Hey, this is the testing email.";
// Those are the values that have the email information
public void send(String from, String pass, String host, String port, String to, String subject, String text) {
Properties props = new Properties();
// Read properties file.
props.put("mail.smtp.user", from);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
Transport.send(msg);
} catch (Exception mex) {
mex.printStackTrace();
}
}
public class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(d_email, d_password);
}
}
}

Check out java.util.Timer and if it is not enough for you read about Quartz - the pure java cron compatible scheduler.

Quartz seems better option.This tutorial might help you to set up quartz.

try
public class SendEmail extends TimerTask{
public static void main(String[] args){
Timer t = new Timer();
t.schedule(new SendEmail(), 0, 9000); //send email every 9 seconds
}
#Override
public void run() {
// TODO Auto-generated method stub
//Your email syntax here
}
}

Related

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.1 Client was not authenticated

I am getting the 'com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.1 Client was not authenticated' error always, can somebody tell me what am I doing wrong in my code?
Properties mailprops = new Properties();
mailprops.setProperty("mail.transport.protocol", "smtp");
mailprops.setProperty("mail.smtp.host", "MyHost");
mailprops.setProperty("mail.smtp.user", "UserName");
mailprops.setProperty("mail.smtp.password", "Password");
Session mailSession = Session.getDefaultInstance(mailprops, null);
MimeMessage message = new MimeMessage(mailSession);
message.setSubject(mySubject);
message.addRecipient(To);
message.addFrom(from address);
try{
Transport.send(message);
}catch (SendFailedException sfe) {
}catch (MessagingException mex) {
}
Try below approach,
Provide the Authenticator object to create the session object
public class MailWithPasswordAuthentication {
public static void main(String[] args) throws MessagingException {
new MailWithPasswordAuthentication().run();
}
private void run() throws MessagingException {
Message message = new MimeMessage(getSession());
message.addRecipient(RecipientType.TO, new InternetAddress("to#example.com"));
message.addFrom(new InternetAddress[] { new InternetAddress("from#example.com") });
message.setSubject("the subject");
message.setContent("the body", "text/plain");
Transport.send(message);
}
private Session getSession() {
Authenticator authenticator = new Authenticator();
Properties properties = new Properties();
properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.host", "mail.example.com");
properties.setProperty("mail.smtp.port", "25");
return Session.getInstance(properties, authenticator);
}
private class Authenticator extends javax.mail.Authenticator {
private PasswordAuthentication authentication;
public Authenticator() {
String username = "auth-user";
String password = "auth-password";
authentication = new PasswordAuthentication(username, password);
}
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}
}
Try something like that:
Transport trans = sess.getTransport("smtp");
try {
String host = sess.getProperty("mail.smtp.host");
String port = sess.getProperty("mail.smtp.port");
String user = sess.getProperty("mail.smtp.user");
String password = sess.getProperty("mail.smtp.password");
int prt = port == null ? -1 : Integer.parseInt(port);
trans.connect(host, prt, user, password);
trans.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
} finally {
trans.close();
}
UPDATE:
Or rather:
int prt = port == null ? 25 : Integer.parseInt(port);
enable authentication.
enable STARTTLS.
create Authenticator object to pass in Session.getInstance argument.
Sample code:
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getInstance(props, auth);
You don't need an Authenticator as some answers suggest. There is no mail.smtp.password property. Call the Transport.send method that takes a username and password.

Failed to connect smtp server

It is showing following error ::
Exception in thread "main" java.lang.RuntimeException:
javax.mail.MessagingException: Could not connect to SMTP host:
localhost, port: 587, response: 421 at
SendMail.main(SendMail.java:54) Caused by:
javax.mail.MessagingException: Could not connect to SMTP host:
localhost, port: 587, response: 421 at
com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2088)
at
com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:699)
at javax.mail.Service.connect(Service.java:388) at
javax.mail.Service.connect(Service.java:246) at
javax.mail.Service.connect(Service.java:195) at
javax.mail.Transport.send0(Transport.java:254) at
javax.mail.Transport.send(Transport.java:124) at
SendMail.main(SendMail.java:49) Java Result: 1 BUILD SUCCESSFUL (total
time: 2 seconds)
and my code is:
`public class SendMail {
public static void main(String[] args) throws Exception{
final String smtp_host = "smtp.gmail.com";
final String smtp_username = "xxx#gmail.com";
final String smtp_password = "xxxxxx";
final String smtp_connection = "TLS";
final String toEmail="xxx#gmail.com";
final String fromEmail="yyy#example.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
if (smtp_connection.equals("TLS")) {
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
} else{
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.port", "465");
}
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(smtp_username, smtp_password);
}
});
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(fromEmail, "NoReply"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmail, "Mr. Recipient"));
msg.setSubject("Welcome To JavaMail API");
msg.setText("JavaMail API Test - Sending email example through remote smtp server");
Transport.send(msg);
System.out.println("Email sent successfully...");
} catch (AddressException e) {
throw new RuntimeException(e);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}`
Below is the working code. You are not setting an SSL socket factory in the non-TLS case.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "username"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "password"; // GMail password
private static String RECIPIENT = "xxxxx#gmail.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "hi ....,!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
To connect to google SMTP server, make sure you are using TLS/SSL. It is required.
Go to gmail account Click on the Forwarding/IMAP tab and scroll down to the IMAP Access section: IMAP must be enabled in order for emails to be properly copied to your sent folder.
And Try Change This
if (smtp_connection.equals("TLS")) {
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
} else{
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.port", "465");
}
To This
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.user", "username"); // User name
properties.put("mail.smtp.password", "password"); // password
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");

Java Email sending API email did not send.. hang up the program

I was code a java email sending program. But when i click the send button the button appear hanging mode & program still running, but mail did not send.
I can't detect the problem. can anybody help me...
The code is below.
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.starttls.enable", "false");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("myid#gmail.com", "password");
}
}
);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("myid#gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("senderid#gmail.com"));
message.setSubject("Demo mail");
message.setText("Hello, world!");
Transport.send(message);
JOptionPane.showMessageDialog(this, "Message sent!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e);
}
My email account have not activate 2-step verification service.
And it also work in outlook email sending software.. I tested.
But not work on my java program.
I believe the Authenticator class should be extended. Here is an example that works for me:
public class SendEmail {
public SendEmail () {}
public void send (String text){
String host = "smtp.gmail.com";
String username = "user#email.com";
String password = "password";
Properties props = new Properties();
// set any needed mail.smtps.* properties here
Session session = Session.getInstance(props, new GMailAuthenticator("user", "password"));
Message msg = new MimeMessage(session);
Transport t;
try {
msg.setText(text);
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("stackkinggame#gmail.com", "Stack King"));
t = session.getTransport("smtps");
t.connect(host, username, password);
t.sendMessage(msg, msg.getAllRecipients());
t.close();
Gdx.app.log("Email", "Message sent successfully.");
}
catch (Exception e) {
e.printStackTrace();
}
}
class GMailAuthenticator extends Authenticator {
String user;
String pw;
public GMailAuthenticator (String username, String password)
{
super();
this.user = username;
this.pw = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
}
First, fix all the common JavaMail mistakes in your program.
Second, since you're using Gmail, make sure you've enabled support for less secure apps.
Finally, you need to provide more details than "it doesn't work". The JavaMail debug output would be helpful.

sending mail using java from pc to mobile

final String username = "<mail_name>";
final String password = "<password>";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("<mail_from>#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("<mail_to>#gmail.com"));
message.setSubject("Test Subject");
message.setText("Test");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
I have tried this code for sending mail from pc to mobile but it giving error while compiling . Can any one help me to send mail?
public class sendmail{
public static void mail(String args[]){
final String fromEmail = ""; //requires valid gmail id
final String password = ""; // correct password for gmail id
final String toEmail = "" // can be any email id
System.out.println("SSLEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
props.put("mail.smtp.port", "465"); //SMTP Port
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getDefaultInstance(props, auth);
System.out.println("Session created");
String subject = "";//subject here
String body = "";//mail body here
sendEmail(session, toEmail, subject, body);
}
public static void sendEmail(Session session, String toEmail, String subject, String body) {
try {
MimeMessage msg = new MimeMessage(session);
//set message headers
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("no-reply#anyname.com", "any name"));
msg.setReplyTo(InternetAddress.parse(toEmail, false));
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport.send(msg);
System.out.println("EMail Sent Successfully!!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("ERROR:" + e.getMessage());
}
}
}
What is mean by PC to Mobile. PC & mobile both are hardware devices to access the mail.Please follow the below link for sending mail in java using java mail API via gmail SMTP.
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

Problem using Java Mail API

I have this servlet which needs to send mail using Java Mail API, however I am getting no password specified error, although the password work with gmail.
MailServiceImpl.java:
public class MailServiceImpl extends RemoteServiceServlet implements MailService {
private static String HOST = "smtp.gmail.com";
private static int PORT = 465;
private String username = "foo#gmail.com";
private String password = "foo123";
private Properties props = new Properties();
#Override
public void sendMail(String email) {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getInstance(props);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("foo#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("foo#gmail.com"));
message.setSubject("Testing Subject");
message.setText("Subcriber Email:," +
"\n\n " + email);
Transport transport = session.getTransport("smtp");
transport.connect(HOST, PORT, username, password);
Transport.send(message);
transport.close(); // -- needed?
} catch (Exception e) {
e.printStackTrace();
}
}
}
However I am getting this error:
javax.mail.AuthenticationFailedException: failed to connect, no password specified?
at javax.mail.Service.connect(Service.java:329)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at com.mygwtapp.server.MailServiceImpl.sendMail(MailServiceImpl.java:43)
Try using SSL connection. It worked for me.
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username","password");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from#test.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to#test.com"));
message.setSubject("Testing Subject");
message.setText("mail text");
Transport.send(message);
System.out.println("OK");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}

Categories