解决错误 javax.mail.AuthenticationFailedException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18778240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:58:26  来源:igfitidea点击:

Solve error javax.mail.AuthenticationFailedException

javajavamail

提问by Fatin Az

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.

我不熟悉这个在java中发送邮件的功能。我在发送电子邮件以重置密码时遇到错误。希望你能给我一个解决方案。

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)

调试:setDebug:JavaMail 版本 1.4.1ea-SNAPSHOT

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

调试 SMTP:useEhlo 真,useAuth 真

调试 SMTP:尝试连接到主机“smtp.gmail.com”,端口 465,isSSL false 220 mx.google.com ESMTP m4sm5929870pbg.38 - gsmtp

调试 SMTP:连接到主机“smtp.gmail.com”,端口:465

EHLO 脂肪

250-mx.google.com 为您服务,[175.139.198.14]

250 码 35882577

250-8BITMIME

250-AUTH 登录 PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN

250 增强状态代码

第250话

调试 SMTP:找到扩展名“SIZE”,参数“35882577”

调试 SMTP:找到扩展名“8BITMIME”,参数“”

调试 SMTP:找到扩展名“AUTH”,arg“LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN”

调试 SMTP:找到扩展“ENHANCEDSTATUSCODES”,参数“”

调试 SMTP:找到扩展名“CHUNKING”,参数“”

调试 SMTP:尝试进行身份验证

授权登录

第334章

YWNjb3VudEBibG9vbWluZy5jb20ubXk=

第334章

Ymxvb21pbmc= 535-5.7.8 用户名和密码不被接受。在 535 5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 上了解详情

m4sm5929870pbg.38 - gsmtp

[标准输出] javax.mail.AuthenticationFailedException

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

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

[标准输出] 在 com.vlee.util.mail.SendMail.sendMailAdvance(SendMail.java:283)

[标准输出] 在 com.vlee.servlet.ecommerce.DoMemberLogin.fnSendPwd(DoMemberLogin.java:251)

[标准输出] 在 com.vlee.servlet.ecommerce.DoMemberLogin.doPost(DoMemberLogin.java:72)

采纳答案by Ha Nguyen

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

您应该将端口更改为587,我测试了您的代码并且它工作正常

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 gerrytan

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/

您的 gmail smtp 设置错误。Gmail 需要 SSL。请参阅有关如何通过 Gmail SMTP 通过 Java 发送电子邮件的教程,例如:http: //www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

回答by Kedar

2 possible reasons:

2个可能的原因:

  • Your username may require the entire email id '[email protected]'
  • Most obvious: The password is wrong. Debug to see if the password being used is correct.
  • 您的用户名可能需要完整的电子邮件 ID '[email protected]'
  • 最明显的是:密码错误。调试以查看所使用的密码是否正确。

回答by Pana Emp

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();
          }
    }

}

回答by Raj008

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

可能是 Gmail 账户保护导致的这个问题。只需单击下面的链接并禁用安全设置。它会起作用。 https://www.google.com/settings/security/lesssecureapps

回答by Anil Amane

回答by sawpyae

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

大多数 AuthenticationFieldException 错误在登录尝试被阻止时发生,首先登录您的 gmail 并转到https://www.google.com/settings/security/lesssecureapps并检查打开。我是这样解决这类问题的。

回答by Anil Muppalla

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.

可以通过为正在使用的帐户激活谷歌两步验证并创建应用程序特定密码来缓解身份验证问题。我遇到了与 OP 相同的问题。启用两步工作。

回答by Vino

I have been getting the same error for long time.

很长一段时间以来,我一直遇到同样的错误。

When i changed session debug to true

当我将会话调试更改为 true 时

Session session = Session.getDefaultInstance(props, new GMailAuthenticator("[email protected]", "xxxxx"));
session.setDebug(true);

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

我从控制台获得了帮助 url https://support.google.com/mail/answer/78754以及 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.

注意:我的旧密码更不安全。

回答by Do Nhu Vy

Change this (set less secure app): https://www.google.com/settings/security/lesssecureapps

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