通过Google的SMTP服务器发送电子邮件时出现问题

时间:2015-06-18 20:10:05

标签: java email smtp gmail javax.mail

当我尝试使用Google的SMTP发送电子邮件时,我收到了身份验证例外。

我的源代码(非常类似于另一个答案):

public static void sendEmail(String to, String subject, String content) {


    String from = "email@gmail.com";
    final String username = "email@gmail.com";
    final String password = "password";


    String host = "smtp.gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "587");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {

            return new PasswordAuthentication(username, password);
        }
    });

    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject: header field
        message.setSubject(subject);

        // Now set the actual message
        message.setText(content);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {
        LOGGER.info("MessagingException in sendEmail:",e);
        throw new RuntimeException(e);
    }
}

我得到的例外是:

Caused by: javax.mail.AuthenticationFailedException: a.b.c.d <https://accounts.google.com/ContinueSignIn?something cryptic> Please log in via your web browser and then try again. Learn more at https://support.google.com/mail/answer/78754
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826) ~[mail-1.5.0-b01.jar:1.5.0-b01]
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761) ~[mail-1.5.0-b01.jar:1.5.0-b01]
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685) ~[mail-1.5.0-b01.jar:1.5.0-b01]
    at javax.mail.Service.connect(Service.java:317) ~[mail-1.5.0-b01.jar:1.5.0-b01]
    at javax.mail.Service.connect(Service.java:176) ~[mail-1.5.0-b01.jar:1.5.0-b01]
    at javax.mail.Service.connect(Service.java:125) ~[mail-1.5.0-b01.jar:1.5.0-b01

根据说明,我允许来自https://www.google.com/settings/security/lesssecureapps

的不太安全的应用

但我仍然遇到同样的错误。可以做些什么来解决这个问题? 我知道密码是正确的,因为我在谷歌帐户上收到了可疑的登录电子邮件。

0 个答案:

没有答案