javax.mail.AuthenticationFailedException:连接失败,未指定密码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6610572/
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-16 08:15:00  来源:igfitidea点击:

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

javasmtpgmailjavax.mail

提问by Suhail Gupta

This program attempts to send e-mail but throws a run time exception:

该程序尝试发送电子邮件但引发运行时异常:

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

Why am I getting this exception when I have supplied the correct username and password for authentication?

当我提供了正确的用户名和密码进行身份验证时,为什么会出现此异常?

Both the sender and receiver have g-mail accounts. The sender and the receiver both have g-mail accounts. The sender has 2-step verification process disabled.

发件人和收件人都有 g-mail 帐户。发件人和收件人都有 g-mail 帐户。发件人已禁用两步验证过程。

This is the code:

这是代码:

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

class tester {
    public static void main(String args[]) {
        Properties props = new Properties();
        props.put("mail.smtp.host" , "smtp.gmail.com");
        props.put("mail.stmp.user" , "username");

        //To use TLS
        props.put("mail.smtp.auth", "true"); 
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.password", "password");
        //To use SSL
        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 , null);
        String to = "[email protected]";
        String from = "[email protected]";
        String subject = "Testing...";
        Message msg = new MimeMessage(session);
        try {
            msg.setFrom(new InternetAddress(from));
            msg.setRecipient(Message.RecipientType.TO, 
                new InternetAddress(to));
            msg.setSubject(subject);
            msg.setText("Working fine..!");
            Transport transport = session.getTransport("smtp");
            transport.connect("smtp.gmail.com" , 465 , "username", "password");
            transport.send(msg);
            System.out.println("fine!!");
        }
        catch(Exception exc) {
            System.out.println(exc);
        }
    }
}

Even after giving the password I get the exception. Why is it not authenticating?

即使在给出密码后,我也得到了例外。为什么不认证?

采纳答案by RMT

Try to create an javax.mail.Authenticator Object, and send that in with the properties object to the Session object.

尝试创建一个 javax.mail.Authenticator 对象,并将其与属性对象一起发送到 Session 对象。

Authenticatoredit:

验证器编辑:

You can modify this to accept a username and password and you can store them there, or where ever you want.

您可以修改它以接受用户名和密码,您可以将它们存储在那里,或者您想要的任何地方。

public class SmtpAuthenticator extends Authenticator {
public SmtpAuthenticator() {

    super();
}

@Override
public PasswordAuthentication getPasswordAuthentication() {
 String username = "user";
 String password = "password";
    if ((username != null) && (username.length() > 0) && (password != null) 
      && (password.length   () > 0)) {

        return new PasswordAuthentication(username, password);
    }

    return null;
}

In your class where you send the email:

在您发送电子邮件的班级中:

SmtpAuthenticator authentication = new SmtpAuthenticator();
javax.mail.Message msg = new MimeMessage(Session
                    .getDefaultInstance(emailProperties, authenticator));

回答by Andrew Calder

It might be worth verifying that the gmail account hasn't been locked out due to several unsuccessful login attempts, you may need to reset your password. I had the same problem as you, and this turned out to be the solution.

可能值得验证 gmail 帐户是否因多次登录尝试失败而被锁定,您可能需要重置密码。我和你有同样的问题,结果这就是解决方案。

回答by Kenny Cason

In addition to RMT's answer. I also had to modify the code a bit.

除了RMT的答案。我还不得不稍微修改一下代码。

  1. Transport.send should be accessed statically
  2. therefor, transport.connect did not do anything for me, I only needed to set the connection info in the initial Properties object.
  1. Transport.send 应该静态访问
  2. 因此,transport.connect 没有为我做任何事情,我只需要在初始 Properties 对象中设置连接信息。

here is my sample send() methods. The config object is just a dumb data container.

这是我的示例 send() 方法。config 对象只是一个愚蠢的数据容器。

public boolean send(String to, String from, String subject, String text) {
    return send(new String[] {to}, from, subject, text);
}

public boolean send(String[] to, String from, String subject, String text) {

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.host", config.host);
    props.put("mail.smtp.user", config.username);
    props.put("mail.smtp.port", config.port);
    props.put("mail.smtp.password", config.password);

    Session session = Session.getInstance(props, new SmtpAuthenticator(config));

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        InternetAddress[] addressTo = new InternetAddress[to.length];
        for (int i = 0; i < to.length; i++) {
            addressTo[i] = new InternetAddress(to[i]);
        }
        message.setRecipients(Message.RecipientType.TO, addressTo);
        message.setSubject(subject);
        message.setText(text);
        Transport.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

回答by Sowmya Vallam

You need to add the Object Authentication as the Parameter to the Session. such as

您需要将对象身份验证作为参数添加到会话中。如

Session session = Session.getDefaultInstance(props, 
    new javax.mail.Authenticator(){
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(
                "[email protected]", "XXXXX");// Specify the Username and the PassWord
        }
});

now You will not get this kind of Exception....

现在你不会得到这种异常....

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

回答by Bharat Sharma

Your email session should be provided an authenticator instance as below

您的电子邮件会话应提供一个身份验证器实例,如下所示

Session session = Session.getDefaultInstance(props,
    new Authenticator() {
        protected PasswordAuthentication  getPasswordAuthentication() {
        return new PasswordAuthentication(
                    "[email protected]", "password");
                }
    });

a complete example is here http://bharatonjava.wordpress.com/2012/08/27/sending-email-using-java-mail-api/

一个完整的例子在这里http://bharatonjava.wordpress.com/2012/08/27/sending-email-using-java-mail-api/

回答by Vishal Nawale

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;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@SuppressWarnings("serial")
public class RegisterAction {


    public String execute() {


         RegisterAction mailBean = new RegisterAction();

           String subject="Your username & password ";

           String message="Hi," + username;
          message+="\n \n Your username is " + email;
          message+="\n \n Your password is " + password;
          message+="\n \n Please login to the web site with your username and password.";
          message+="\n \n Thanks";
          message+="\n \n \n Regards";

           //Getting  FROM_MAIL

           String[] recipients = new String[1];
            recipients[0] = new String();
            recipients[0] = customer.getEmail();

           try{
          mailBean.sendMail(recipients,subject,message);

          return "success";
          }catch(Exception e){
           System.out.println("Error in sending mail:"+e);
          }

        return "failure";
    }

    public void sendMail( String recipients[ ], String subject, String message)
             throws MessagingException
              {
                boolean debug = false;

                 //Set the host smtp address

                 Properties props = new Properties();
                 props.put("mail.smtp.host", "smtp.gmail.com");
                 props.put("mail.smtp.starttls.enable", true);
                 props.put("mail.smtp.auth", true);

                // create some properties and get the default Session

                Session session = Session.getDefaultInstance(props, new Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(
                                "[email protected]", "5373273437543");// Specify the Username and the PassWord
                    }

                });
                session.setDebug(debug);


                // create a message
                Message msg = new MimeMessage(session);


                InternetAddress[] addressTo = new InternetAddress[recipients.length];
                for (int i = 0; i < recipients.length; i++)
                {
                  addressTo[i] = new InternetAddress(recipients[i]);
                }

                msg.setRecipients(Message.RecipientType.TO, addressTo);

                // Optional : You can also set your custom headers  in the Email if you Want
                //msg.addHeader("MyHeaderName", "myHeaderValue");

                // Setting the Subject and Content Type
                msg.setSubject(subject);
                msg.setContent(message, "text/plain");

                //send message
                Transport.send(msg);

                System.out.println("Message Sent Successfully");
              }

}

回答by user2618037

I have just faced this problem, and the solution is that the property "mail.smtp.user" should be your email (not username).

我刚刚遇到了这个问题,解决方案是属性“mail.smtp.user”应该是您的电子邮件(而不是用户名)。

The example for gmail user:

gmail 用户的示例:

properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.user", from);
properties.put("mail.smtp.password", pass);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");

回答by alecswan

Even when using an Authenticator I had to set mail.smtp.auth property to true. Here is a working example:

即使在使用身份验证器时,我也必须将 mail.smtp.auth 属性设置为 true。这是一个工作示例:

final Properties props = new Properties();
props.put("mail.smtp.host", config.getSmtpHost());
props.setProperty("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator()
{
  protected PasswordAuthentication getPasswordAuthentication()
  {
    return new PasswordAuthentication(config.getSmtpUser(), config.getSmtpPassword());
  }
});

回答by user4083502

I also have this problem so don't worry. It comes from mail server side due to an outside authentication issue. Open your mail and you will get a mail from the mail server telling you to enable accessibility. When you have done that, retry your program.

我也有这个问题,不用担心。由于外部身份验证问题,它来自邮件服务器端。打开您的邮件,您将从邮件服务器收到一封邮件,告诉您启用可访问性。完成后,重试您的程序。

回答by T30

I've solved this issue adding user and passwordin Transport.sendcall:

我已经解决了在通话中添加用户和密码的问题Transport.send

Transport.send(msg, "user", "password");


According to this signature of the sendfunctionin javax.mail (from version 1.5):

根据javax.mail 中send函数的这个签名(1.5 版开始):

public static void send(Message msg, String user, String password)

public static void send(Message msg, String user, String password)

Also, if you use this signature it's not necessary to set up any Authenticator, and to set user and password in the Properties(only the host is needed). So your code could be:

此外,如果您使用此签名,则无需设置任何Authenticator, 并在其中设置用户和密码Properties(仅需要主机)。所以你的代码可能是:

private void sendMail(){
  try{
      Properties prop = System.getProperties();
      prop.put("mail.smtp.host", "yourHost");
      Session session = Session.getInstance(prop);
      Message msg = #createYourMsg(session, from, to, subject, mailer, yatta yatta...)#;
      Transport.send(msg, "user", "password");
  }catch(Exception exc) {
      // Deal with it! :)
  }
}