2017-04-14 82 views
0

我想從我的Java應用程序發送電子郵件至Gmail帳戶我用下面的代碼的JavaMail API,但是Gmail不接受用戶名和密碼,並拋出異常 任何人可以幫助我我該如何解決這個問題?的JavaMail API:用戶名與密碼不正確(如Gmail)

MailService.java

public class MailService { 

    String email; 
    String content; 
    public void sendMail(String email,String content) 
    { 
     this.email=email; 
     this.content=content; 
     // Recipient's email ID needs to be mentioned. 
      String to = email; 

      // Sender's email ID needs to be mentioned 
      String from = [email protected]; 
      final String username = "myusername";//change accordingly 
      final String password = "*******";//change accordingly 

      // Assuming you are sending email through relay.jangosmtp.net 
      String host = "smtp.gmail.com"; 

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

      // Get the Session object. 
      Session session = Session.getInstance(props, 
      new javax.mail.Authenticator() { 
       protected PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication(username, password); 
      } 
      }); 

      try { 
      // Create a default MimeMessage object. 
      Message message = new MimeMessage(session); 

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

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

      // Set Subject: header field 
      message.setSubject("Did you get my message?"); 

      // Now set the actual message 
      message.setText(content); 

      // Send message 
      Transport.send(message); 

      System.out.println("Sent message successfully...."); 

      } catch (MessagingException e) { 
      throw new RuntimeException(e); 
      } 
     } 
    } 
+1

的可能的複製[JavaMail的與Gmail:535-5.7.1用戶名和密碼不被接受(http://stackoverflow.com/questions/2965251/javamail-with-gmail-535-5-7-1-username - 和密碼 - 不接受) –

回答

1

要通過Gmail帳戶可以發送郵件,你應該允許不安全的應用程序(應用程序是Gmail的角度來看)的谷歌帳戶的安全設置。 enter image description here

UPD: 另外,如果你想看到調試消息,下次使用Java郵件屬性:

props.put("mail.debug", "true"); 

它可以幫助你找出幕後發生了什麼。

+1

這和很多相關的主題涵蓋了[JavaMail的FAQ(http://www.oracle.com/technetwork/java/javamail/faq/index.html#gmailauth)。 –

相關問題