我正在尝试从“ smtp.mail.yahoo.com”发送电子邮件。我尝试使用不同的端口号,例如587、465等。当我使用gmail主机发送邮件时,它工作正常。但是当我尝试使用yahoo时,出现了以下异常。
package com.java.sample.workouts;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.PasswordAuthentication;
import java.util.Properties;
public class JavaSendEmail {
private static final String SMTP_HOST_NAME = "smtp.mail.yahoo.com";
private static final String SMTP_AUTH_USER = "myyahooid@yahoo.com";
private static final String SMTP_AUTH_PWD = "mypassword";
public static void main(String[] args) throws Exception{
new JavaSendEmail().test();
}
public void test() throws Exception{
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.ssl","true");
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(SMTP_AUTH_USER, SMTP_AUTH_PWD);
}
});
Transport transport = session.getTransport("smtp");
MimeMessage message = new MimeMessage(session);
message.setContent("This is a test", "text/plain");
message.setFrom(new InternetAddress("myyahooid@yahoo.com"));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("myyahooid@yahoo.com"));
transport.connect();
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
}
}
但是我遇到了以下异常
Exception in thread "main" javax.mail.AuthenticationFailedException: 535 5.7.1 Authentication failed
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:823)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:756)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:673)
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 com.java.sample.workouts.JavaSendEmail.test(JavaSendEmail.java:46)
at com.java.sample.workouts.JavaSendEmail.main(JavaSendEmail.java:18)
答案 0 :(得分:0)
请按照以下步骤在您的Yahoo帐户中启用“不太安全的应用”:
我刚刚测试了您的代码,并且可以正常工作