无法使用Java程序将邮件发送到gmail

时间:2014-12-20 13:56:00

标签: java smtp

无法使用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();

    }

} 

1 个答案:

答案 0 :(得分:0)

查看this页面。它有一个完整的例子,您可以根据自己的需要进行更改。还可以尝试查看问题是否可以通过this问题解决。

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

希望这会有所帮助。