如何使用 smtp.mail.yahoo.com 发送 Java 电子邮件?

How to send Java email using smtp.mail.yahoo.com?

我正在尝试从 "smtp.mail.yahoo.com" 发送电子邮件。我尝试使用不同的端口号,如 587、465 等,当我使用 gmail 主机发送时它工作正常。但是当我尝试使用雅虎时,出现以下异常。

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)

按照以下步骤在您的 Yahoo 帐户中启用不太安全的应用程序:

  1. 转到帐户信息
  2. Select“账户安全”
  3. 启用“允许使用安全性较低的应用程序 登录”

我刚刚测试了您的代码,它可以正常工作