I want to create a function that can send email to any specified recipient (gmail). The problem I am facing is my authentication when I try to provide credentials that use two-way authentication in gmail. Since the account does not have two-way authentication, it works fine. So what do I need to do to make things happen with two-way authentication?
Below is the code that I use 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; } }
source share