I want to make a function which can send email to any specified recipient(gmail). The problem I am facing is my authentication fails when I try to provide credentials which uses two way authentication in gmail. With account having no two way authentication it works fine. So what I have to do to make things happen with two way authentications enabled?
Following is the code which I am using to send email.
public static boolean sendMail(String fromMail, String fromPassword, String toMail, String message) {
try {
final String user = fromMail, password = fromPassword;
Properties prop = new Properties();
prop.setProperty("mail.smtp.host", "smtp.gmail.com");
prop.setProperty("mail.smtp.port", "465");
prop.setProperty("mail.smtp.auth", "true");
prop.setProperty("mail.smtp.ssl.enable", "true");
// prop.put("mail.debug", "true");
// prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session sess = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(user, password);
}
});
// Session sess=Session.getDefaultInstance(prop);
sess.setDebug(true);
Message msg = new MimeMessage(sess);
msg.setFrom(new InternetAddress(fromMail));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
msg.setText(message);
msg.setContent(message, "text/html");
Transport.send(msg);
return true;
} catch (MessagingException msgEx) {
msgEx.printStackTrace();
return false;
}
}
By creating an application specific password at https://accounts.google.com/IssuedAuthSubTokens. Also check out this youtube video on application specific passwords.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With