我有一个看似非常简单的代码,尝试使用我的Gmail帐户从我的Java应用程序发送电子邮件。当我运行它时,它会以异常javax.mail.AuthenticationFailedException
崩溃。这是代码:
// Recipient's email ID needs to be mentioned.
String to = "fredxya@gmail.com";
// Sender's email ID needs to be mentioned
String from = "johnxyzn@gmail.com";
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("fredxyz@gmail.com","password");
}
});
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("Test Subject");
// Now set the actual message
message.setText("this is a test");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
System.out.println (mex) ;
mex.printStackTrace();
}
答案 0 :(得分:1)
问题是我在Gmail中使用了两步验证。解决方案是使用特定于应用程序的密码(ASP):https://accounts.google.com/IssuedAuthSubTokens?hide_authsub=1
答案 1 :(得分:0)
我能够使用gmail使用TLS发送消息,具有以下属性:
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");
也许它会对你有用。