Sending email through java in a gmail account with two-way authentication

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; } } 
+6
source share
2 answers

By creating a special app password at https://accounts.google.com/IssuedAuthSubTokens . Also check this youtube video for specific app passwords.

+5
source

There are two solutions for this:

  • You can generate a password for a specific application using the link specified by "friek", that is, "https://accounts.google.com/IssuedAuthSubTokens" and use the generated password for a specific application instead of your original password . I did it and his job

or

  • The reason that an Exception (javax.mail.AuthenticationFailedException: 535-5.7.1) is required is because you can activate two-step authentication of your gmail account. If you use an account in which you do not activate 2-step verification, you can send an email with your original password. I also tried this and his work.
+2
source

Source: https://habr.com/ru/post/904415/


All Articles