使用Java发送电子邮件时的AuthenticationFailedException

时间:2014-10-09 06:42:09

标签: java spring javamail

我正在尝试使用java API发送电子邮件,我正在提供正确的emailid和密码,但我仍然收到AuthenticationFailedException。

我也试过给host = mail.smtp.port并将端口更改为587,但我最终得到同样的错误..

请在我出错的地方帮帮我..?

public class SendEmail
   {
   public static void main(String [] args)
   {    
  // Recipient's email ID needs to be mentioned.
  String to = "to@gmail.com";

  // Sender's email ID needs to be mentioned
  final String from = "from@gmail.com";

  // Assuming you are sending email from localhost
  final String host = "smtp.googlemail.com";

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

  // Setup mail server
  properties.setProperty("mail.smtp.host", host);
  properties.setProperty("mail.smtp.starttls.enable", "true");
  properties.setProperty("mail.smtp.user", from);
  //properties.setProperty("mail.smtp.password", "xyz");

  properties.setProperty("mail.debug", "false");
  properties.setProperty("mail.smtp.auth", "true"); 
//  properties.setProperty("mail.smtp.port", "587");

  // Get the default Session object.
 // Session session = Session.getDefaultInstance(properties);

  Session session = Session.getInstance(properties,
          new javax.mail.Authenticator() {

              protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication(from, "xyz");
              }
          });

  session.setDebug(true);

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


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

错误:

javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:306)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at javax.mail.Transport.send0(Transport.java:168)
at javax.mail.Transport.send(Transport.java:98)

1 个答案:

答案 0 :(得分:3)

只需检查您是否已启用来自" Less Secure Apps"使用this link。需要为帐户from@gmail.com启用此设置。