简体   繁体   中英

Solve error javax.mail.AuthenticationFailedException

I'm not familiar with this function to send mail in java. I'm getting an error while sending email to reset a password. Hope you can give me a solution.

Below is my code:

public synchronized static boolean sendMailAdvance(String emailTo, String subject, String body)
{
    String host = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-ADDRESS");
    String userName = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-USERNAME");
    String password = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-PASSWORD");
    String port = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-PORT");
    String starttls = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-STARTTLS");
    String socketFactoryClass = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-SOCKET-CLASS");
    String fallback = AppConfigManager.getProperty("SENDER-EMAIL-SMTP-ALLOW-FALLBACK");                         

    try
    {
        java.util.Properties props = null;
        props = System.getProperties();
        props.put("mail.smtp.user", userName);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.debug", "true");

        if(!"".equals(port))
        {
            props.put("mail.smtp.port", port);
            props.put("mail.smtp.socketFactory.port", port);
        }

        if(!"".equals(starttls))
            props.put("mail.smtp.starttls.enable",starttls);

        if(!"".equals(socketFactoryClass))                   
            props.put("mail.smtp.socketFactory.class",socketFactoryClass);

        if(!"".equals(fallback))
            props.put("mail.smtp.socketFactory.fallback", fallback);

        Session session = Session.getDefaultInstance(props, null);
        session.setDebug(true);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(userName));
        msg.setSubject(subject);                
        msg.setText(body, "ISO-8859-1");
        msg.setSentDate(new Date());
        msg.setHeader("content-Type", "text/html;charset=\"ISO-8859-1\"");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo));
        msg.saveChanges();

        Transport transport = session.getTransport("smtp");
        transport.connect(host, userName, password);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
            return true;
    }
    catch (Exception mex)
    {
        mex.printStackTrace();
        return false;
    }
}

Throws the following error:

DEBUG: setDebug: JavaMail version 1.4.1ea-SNAPSHOT

 DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]

DEBUG SMTP: useEhlo true, useAuth true

DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL false 220 mx.google.com ESMTP m4sm5929870pbg.38 - gsmtp

DEBUG SMTP: connected to host "smtp.gmail.com", port: 465

EHLO fatin

250-mx.google.com at your service, [175.139.198.14]

250-SIZE 35882577

250-8BITMIME

250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN

250-ENHANCEDSTATUSCODES

250 CHUNKING

DEBUG SMTP: Found extension "SIZE", arg "35882577"

DEBUG SMTP: Found extension "8BITMIME", arg ""

DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN"

DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""

DEBUG SMTP: Found extension "CHUNKING", arg ""

DEBUG SMTP: Attempt to authenticate

AUTH LOGIN

334 VXNlcm5hbWU6

YWNjb3VudEBibG9vbWluZy5jb20ubXk=

334 UGFzc3dvcmQ6

Ymxvb21pbmc= 535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257

m4sm5929870pbg.38 - gsmtp

[STDOUT] javax.mail.AuthenticationFailedException

[STDOUT] at javax.mail.Service.connect(Service.java:319)

[STDOUT] at javax.mail.Service.connect(Service.java:169)

[STDOUT] at com.vlee.util.mail.SendMail.sendMailAdvance(SendMail.java:283)

[STDOUT] at com.vlee.servlet.ecommerce.DoMemberLogin.fnSendPwd(DoMemberLogin.java:251)

[STDOUT] at com.vlee.servlet.ecommerce.DoMemberLogin.doPost(DoMemberLogin.java:72)

May be this problem cause by Gmail account protection. Just click below link and disable security settings.It will work. https://www.google.com/settings/security/lesssecureapps

You should change the port to 587 , I tested your code and it's working fine

If error still happens, please change session variable to code below:

Session session = Session.getInstance(props, new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, password);
    }
});

By default Gmail account is highly secured. When we use gmail smtp from non gmail tool, email is blocked. To test in our local environment, make your gmail account less secure as

  1. Login to Gmail.
  2. Access the URL as https://www.google.com/settings/security/lesssecureapps
  3. Select "Turn on"

Most of AuthenticationFieldException Error occur when sign-in attempted prevented, login your gmail first and go to https://www.google.com/settings/security/lesssecureapps and check turn on. I solved this kind of problem like this way.

If you are logging in to your gmail account from a new application or device, Google might be blocking that device. Try following these steps:

To protect your account, Google might make it harder to sign in to your account if we suspect it isn't you. For example, Google might ask for additional information besides your username and password if you are traveling or if you try to sign in to your account from a new device.

Go to https://g.co/allowaccess from a different device you have previously used to access your Google account and follow the instructions. Try signing in again from the blocked app.

更改此设置(设置不太安全的应用程序): https ://www.google.com/settings/security/lesssecureapps

There are a few steps you have to keep in mind.

Now there are two scenarios If you are developing it in your local machine login to your google account in your browser, this way the google recognizes the machine.

If you have deployed the application onto a server then after the first request you will get an authentication error, so you have to give access to the server, just go here to give access- https://www.google.com/accounts/DisplayUnlockCaptcha

The solution that works for me has two steps.

  1. First step

    package com.student.mail; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /** * * @author jorge santos */ public class GoogleMail { public static void main(String[] args) { Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("conaderindicadores@gmail.com","Silueta95#"); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("conaderindicadores@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("netneillip@gmail.com")); message.setSubject("Testing Subject"); message.setText("Test Mail"); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } }
  2. Enable the gmail security

    https://myaccount.google.com/u/2/lesssecureapps?pli=1&pageId=none

I have been getting the same error for long time.

When i changed session debug to true

Session session = Session.getDefaultInstance(props, new GMailAuthenticator("xxxxx@gmail.com", "xxxxx"));
session.setDebug(true);

I got help url https://support.google.com/mail/answer/78754 from console along with javax.mail.AuthenticationFailedException.

From the steps in the link, I followed each steps. When I changed my password with mix of letters, numbers, and symbols to be my surprise the email was generated without authentication exception.

Note: My old password was more less secure.

2 possible reasons:

  • Your username may require the entire email id 'username@example.com'
  • Most obvious: The password is wrong. Debug to see if the password being used is correct.
trying to connect to host "smtp.gmail.com", port 465, isSSL false

You got your gmail smtp setting wrong. Gmail requires SSL. Please see tutorials on how to send email via Java via Gmail SMTP, eg: http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

Just in case anyone comes looking a solution for this problem.

The Authentication problems can be alleviated by activating the google 2-step verification for the account in use and creating an app specific password. I had the same problem as the OP. Enabling 2-step worked.

I had this issue as well but the solution had nothing to do with coding. Make sure you are able to connect to gmail. Ping smtp.gmail.com. If you don't get a reply check your firewall settings. It could also be a proxy setting issue.

Implement Three things with given SMTP settings

  1. Disable two factor aunthentication: https://myaccount.google.com/security
  2. Allow less secure apps : https://www.google.com/settings/security/lesssecureapps
  3. Allow new devices using the link: https://g.co/allowaccess

SMTP Settings:

  • smtp.gmail.com
  • Port: 465
  • Use SSL
  • From Email Address
  • Gmail Username
  • Gmail Password
  • Recepient Email Address

This is because our application cant bypass 2-step verification. If you are using Gmail then here's a solution. Click Manage your google account

Go to "Manage your Google Account"

Click Security Menu item

Go into Security Tab and enable 2-Step verification if not already enabled.

Navigate to App passwords

Select a name and generate the password. Copy the 16 letter password before you close the next window. Select Other

I finally did it. Google doesn't allow third party apps to sign in using your actual password (since March 30th 2022 I think). You have to create an appPassword for your app in gmail. Go to manage accounts in gmail, if you haven't allowed two step verification you'll have to, then the option for creating app password will appear. You'll just type in your app's name and tap the 'generate' button. Your password will popup and you will put it down somewhere. This is the password to be used in the Authentication anonymous class up there in the question.

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendMail1 {

    public static void main(String[] args) {
        // Recipient's email ID needs to be mentioned.
          String to = "valid email to address";

          // Sender's email ID needs to be mentioned
          String from = "valid email from address";


          // Get system properties
          Properties properties = System.getProperties();

          properties.put("mail.smtp.starttls.enable", "true"); 
          properties.put("mail.smtp.host", "smtp.gmail.com");

          properties.put("mail.smtp.port", "587");
          properties.put("mail.smtp.auth", "true");
          Authenticator authenticator = new Authenticator () {
                public PasswordAuthentication getPasswordAuthentication(){
                    return new PasswordAuthentication("userid","password");//userid and password for "from" email address 
                }
            };

            Session session = Session.getDefaultInstance( properties , authenticator);  
          try{
             // Create a default MimeMessage object.
             MimeMessage message = new MimeMessage(session);

             // Set From: header field of the header.
             message.setFrom(new InternetAddress(from));

             // Set To: header field of the header.
             message.addRecipient(Message.RecipientType.TO,
                                      new InternetAddress(to));

             // Set Subject: header field
             message.setSubject("This is the Subject Line!");

             // Now set the actual message
             message.setText("This is actual message");

             // Send message
             Transport.send(message);
             System.out.println("Sent message successfully....");
          }catch (MessagingException mex) {
             mex.printStackTrace();
          }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM