This program attempts to send e-mail but throws a run time exception:
javax.mail.AuthenticationFailedException: failed to connect, no password specified?
First of all, enable the less secure app in your Gmail account from which you will send emails using this link:- https://myaccount.google.com/lesssecureapps?pli=1
Then you simply add the following code in your session creation. It will work fine then.
Session mailSession = Session.getInstance(props, new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"your_email", "your_password");// Specify the Username and the PassWord
}
});
if you want the more elaborated one use the following:-
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class MailSender {
public Properties mailProperties() {
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.user", "your_email");
props.setProperty("mail.smtp.password", "your_password");
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty("mail.smtp.auth", "true");
return props;
}
public String sendMail(String from, String to, String subject, String msgBody) {
Properties props = mailProperties();
Session mailSession = Session.getInstance(props, new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"your_email", "your_password");// Specify the Username and the PassWord
}
});
mailSession.setDebug(false);
try {
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject(subject);
message.setFrom(new InternetAddress(from));
message.addRecipients(Message.RecipientType.TO, to);
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(msgBody, "text/html");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
transport.connect();
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
return "SUCCESS";
} catch (NoSuchProviderException e) {
e.printStackTrace();
return "INVALID_EMAIL";
} catch (MessagingException e) {
e.printStackTrace();
}
return "ERROR";
}
public static void main(String args[]) {
System.out.println(new MailSender().sendMail("your_email/from_email", "to_email", "Subject", "Message"));
}
}
Hope! it helps. Thanks!