当我调用发送方法时(设置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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗...
对此有两种解决方案:
您可以通过链接“https://accounts.google.com/IssuedAuthSubTokens”生成应用程序特定密码,并 使用生成的应用程序特定密码代替原始密码 。我已经完成了这个及其工作
或者
出现异常(javax.mail.AuthenticationFailedException:535-5.7.1需要应用程序特定密码)的原因是您可能已经激活了gmail帐户的两步验证。如果您使用的帐户未激活两步验证,则可以使用原始密码发送电子邮件。我也尝试过这个并且工作正常。