Send mail using Gmail from Java without enabling less secure app

I am trying to send mail using Java to a Gmail account, the code is below. I seem to be doing everything right, however I get an authentication failure. Google wants me to enable the "less secure app" feature to enable transmission.

Is there a way to code it in such a way that Gmail is happy with Java and does not give up the "include less secure apps" opt-out?

Mistake:

javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=...U
534-5.7.14 FigguJaZwDtp...
534-5.7.14 ...o> Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14  Learn more at
534 5.7.14  https://support.google.com/mail/answer/... - gsmtp

      

code:

String hostSmtpUser = "myemail@gmail.com";
String host = "smtp.gmail.com";
String hostPort = "587";
String hostSmtpPassword = "thepassword";

Properties properties = System.getProperties();
properties.setProperty("mail.smtp.user", hostSmtpUser);
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.port", hostPort);
properties.setProperty("mail.smtp.auth", "true");

Session oSession;
if (true == ToolsCommon.isEmpty(hostSmtpUser))
    oSession = Session.getInstance(properties);
else
    oSession = Session.getInstance(properties, new javax.mail.Authenticator()
    {
        protected PasswordAuthentication getPasswordAuthentication()
        {
        return new PasswordAuthentication(hostSmtpUser, hostSmtpPassword);
        }
    });

// Compose the message  
try
{
    MimeMessage message = new MimeMessage(oSession);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(Subject);
    message.setText(Body);

    // Send message  
    Transport.send(message);
}

catch (MessagingException ex)
{
    // Log the error.
    ToolsLog.logError(TypeLog.ui, ex);
}

      

I've already done some research, so the code I know is not the problem, just don't see a workaround for a less secure application.

Literature:

Ref 1 Ref 2 Ref 3 Ref 4

+3


source to share


1 answer


By default GMail does not allow password-based authentication - so you will need to allow "less secure applications" to use your program as is.



Instead, you can use OAuth 2.0 to avoid using a password directly. This method is considered protected by Google and does not require any changes to your account settings.

+1


source







All Articles