这段代码是从http://www.tutorialspoint.com/javamail_api/javamail_api_sending_simple_email.htm
中选取的//package com.tutorialspoint;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "ABC@gmail.com";
// Sender's email ID needs to be mentioned
String from = "PQR@gmail.com";
final String username = "NAME";
final String password = "****";
// Assuming you are sending email through relay.jangosmtp.net
String host = "relay.jangosmtp.net";
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", "25");
// 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("Testing Subject");
// Now set the actual message
message.setText("Hello, this is sample for to check send "
+ "email using JavaMailAPI ");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
我尝试从this链接获取提示。但它似乎使用了略有不同的方法。
在使用调试器运行它时,异常似乎来自以下代码:
Transport.send(message);
以下是堆栈跟踪:
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:809)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:752)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:669)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at SendEmail.main(SendEmail.java:58)
PS:我已经检查了用户名和密码。此外,我没有为我尝试发送邮件的帐户启用2步登录过程。
有人可以解释可能导致认证失败的原因吗?或者,如果有其他帖子已经回答了查询,请指出。感谢。
答案 0 :(得分:0)
服务器对您使用的用户名或密码不满意。您可能会猜到可能出现这种情况的常见原因,并提供错误的用户名或密码。
JavaMail Session debugging output可能会提供更多信息。
答案 1 :(得分:0)
更改String host = "relay.jangosmtp.net";
到String host = "smtp.gmail.com";
和从25
到587
的端口