【问题标题】:Unable to send mail to gmail using Java program无法使用 Java 程序向 gmail 发送邮件
【发布时间】:2015-02-19 06:22:17
【问题描述】:

无法使用 Java 程序向 gmail 帐户发送邮件,这是给AuthenticationFailedException 根本原因:

javax.mail.SendFailedException: Sending failed;
  nested exception is:
    class javax.mail.AuthenticationFailedException
    at javax.mail.Transport.send0(Transport.java:218)
    at javax.mail.Transport.send(Transport.java:80)
    at com.sekhar.mail.SendMail.<init>(SendMail.java:32)
    at com.sekhar.mail.SendMail.main(SendMail.java:48)

在这里查看程序:

public class SendMail {

    public SendMail() {
        // TODO Auto-generated constructor stub
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        try {
            Authenticator auth = new SMTPAuthenticator();

            Session session = Session.getInstance(props,auth);
            MimeMessage msg = new MimeMessage(session);
            msg.setSubject("Open");
            msg.setFrom(new InternetAddress("***@gmail.com"));
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress("***@gmail.com"));
            msg.setText("How are you");
            Transport.send(msg);
            System.out.println("Mail Delivered......");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    private class SMTPAuthenticator extends Authenticator{
        public PasswordAuthentication getPasswordAuthentication(){
            return new PasswordAuthentication("***@gmail.com","****");
        }
    }
    public static void main(String[] args) {

        SendMail mail = new SendMail();

    }

} 

【问题讨论】:

  • 您是否在用于发送电子邮件的 Gmail 帐户中设置了两步验证
  • 你的代码对我很好。检查您的身份验证。

标签: java smtp


【解决方案1】:

看看this 页面。它有一个完整的示例,您可以根据需要进行更改。也可以试试this问题是否能解决问题。

在第一个链接上,它显示端口应该是 587,而不是 465。两个链接都使用带有props.put("mail.smtp.starttls.enable", "true"); 的 ttls。

希望这会有所帮助。

【讨论】:

  • 这应该是一条评论
  • 仅链接的答案无效。最好包含链接并提供链接以供进一步参考的相关表格。
  • 我没用过JavaMail...只是想帮忙!
猜你喜欢
  • 2021-01-27
  • 1970-01-01
  • 2016-10-28
  • 1970-01-01
  • 1970-01-01
  • 2018-11-08
  • 2014-10-23
  • 2016-11-06
  • 2018-11-14
相关资源
最近更新 更多