尝试使用gmail以Java发送电子邮件总是导致用户名和密码不被接受

当我调用send方法时(在设置studentAddress之后),我得到了这个:

javax.mail.AuthenticationFailedException: 535-5.7.1 Username and Password not accepted. Learn more at
535 5.7.1 http://mail.google.com/support/bin/answer.py?answer=14257 y15sm906936wfd.10

我很确定代码是正确的,100%肯定我输入的用户名和密码详细信息是正确的。 那么这个gmail有什么不对吗?

这是我的代码:

 import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class SendEmail { private String host = "smtp.gmail.com"; private String emailLogin = "xxx@gmail.com"; private String pass = "xxx"; private String studentAddress; private String to; private Properties props = System.getProperties(); public SendEmail() { props.put("mail.smtps.auth", "true"); props.put("mail.smtps.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", emailLogin); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "587"); to = "xxx@gmail.com"; } public void setStudentAddress(String newAddress) { studentAddress = newAddress; } public void send() { Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(emailLogin)); InternetAddress[] studentAddressList = {new InternetAddress(studentAddress)}; message.setReplyTo(studentAddressList); message.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Test Email"); message.setText("This is a test email!"); Transport transport = session.getTransport("smtps"); transport.connect(host, emailLogin, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (MessagingException me) { System.out.println("There has been an email error!"); me.printStackTrace(); } } } 

有任何想法吗…

这有两个解决方案:

您可以通过链接生成应用程序专用密码,即“https://accounts.google.com/IssuedAuthSubTokens”,并使用生成的应用程序专用密码替换原始密码 。 我已经完成了这项工作

要么

出现exception(javax.mail.AuthenticationFailedException:535-5.7.1特定于应用程序的密码)的原因是您可能已激活gmail帐户的两步validation。 如果您使用的帐户未激活两步validation,则可以使用原始密码发送电子邮件。 我也试过这个,它的工作正常。

我确实遇到了同样的问题(使用commons-email确实比使用java.mail更容易)。 为我解决的是更改用户名以包含user@mydomain.com而不仅仅是“user”。 可能是一个新的错误,但也许其他人可以从中受益。

问题与gmail有关,而不是代码!

在您的程序中使用gmail帐户存在某些限制。 其中一个是帐户应该有几天了,我想它的1天。