我正在尝试使用 java API 发送电子邮件,并且提供了正确的电子邮件 ID 和密码,但仍然收到 AuthenticationFailedException。
我还尝试提供 host=mail.smtp.port 并将端口更改为 587,但我最终还是遇到了相同的错误..
请帮助我哪里出错了..?
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "to@gmail.com";
// Sender's email ID needs to be mentioned
final String from = "from@gmail.com";
// Assuming you are sending email from localhost
final String host = "smtp.googlemail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.user", from);
//properties.setProperty("mail.smtp.password", "xyz");
properties.setProperty("mail.debug", "false");
properties.setProperty("mail.smtp.auth", "true");
// properties.setProperty("mail.smtp.port", "587");
// Get the default Session object.
// Session session = Session.getDefaultInstance(properties);
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "xyz");
}
});
session.setDebug(true);
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("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
// Transport.send(message);
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
错误:
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)
最佳答案
只需检查您是否已使用this link启用从“不太安全的应用程序”登录。需要为帐户 from@gmail.com
启用此设置。
关于java - 使用 Java 发送电子邮件时出现 AuthenticationFailedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26271923/