簡體   English   中英

使用Java發送電子郵件時出現AuthenticationFailedException

[英]AuthenticationFailedException while sending email using Java

我正在嘗試使用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)

只需使用此鏈接檢查是否已從“ Less Secure Apps”啟用登錄。 需要為from@gmail.com帳戶啟用此設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM