2012-12-10 54 views
1

我尝试使用下面的代码发送邮件,但我得到异常像。如何解决javax.mail.AuthenticationFailedException?

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) 
    at mail.MailTest.sendMailSSL(MailTest.java:116) 

请任何人帮我,我该如何解决它。

这里是我的code.Thanks

String mailBODY = "<h3>Hi this is my test Mail</h3>; 

     final String username = "[email protected]"; 
     final String password = "password"; 

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

     Session session = Session.getInstance(props, new GMailAuthenticator(username, password)); 

     try { 

      Message message = new MimeMessage(session); 
      message.setFrom(new InternetAddress("TEST")); 
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse([email protected])); 
      message.setSubject("Mail subject test"); 
      message.setContent(mailBODY,"text/html; charset=utf-8"); 

      Transport.send(message); 
      System.out.println("mail has been send"); 

     } catch (MessagingException e) { 
      e.printStackTrace(); 
     } 

回答

2

尝试增加道具和发送这样的:

  Properties props = System.getProperties(); 
      props.put("mail.smtp.starttls.enable", "true"); 
      props.put("mail.smtp.host", host); 
      props.put("mail.smtp.user", from); 
      props.put("mail.smtp.password", pass); 
      props.put("mail.smtp.port", "587"); 
      props.put("mail.smtp.auth", "true"); 
// ... 
Session session = Session.getDefaultInstance(props, null); 
      MimeMessage message = new MimeMessage(session); 
// ... 

Transport transport = session.getTransport("smtp"); 
      transport.connect(host, from, pass); 
      transport.sendMessage(message, message.getAllRecipients()); 
      transport.close(); 
+0

后,我得到这个错误谢谢你的回答,但同样的例外,我发现 – Narendra

+0

在这种情况下,它会留下2个可能的原因:1.您的用户/传递错误。重新检查它。 2.您的邮件服务器有一些限制机制来拒绝您的登录。尝试联系Gmail支持人员,询问他们为什么阻止了你。因为唯一的事实是登录被Gmail拒绝(看起来这是你的邮件提供商) – urir

1

我启用了两步验证我的谷歌帐户

相关问题