1

我尝试使用下面的代码发送邮件,但我收到了类似的异常。

javax.mail.AuthenticationFailedException
    at javax.mail.Service.connect(Service.java:306)
    at javax.mail.Service.connect(Service.java:156)
    at javax.mail.Service.connect(Service.java:105)
    at javax.mail.Transport.send0(Transport.java:168)
    at javax.mail.Transport.send(Transport.java:98)
    at mail.MailTest.sendMailSSL(MailTest.java:116)

请任何人帮助我如何解决它。

这是我的代码。谢谢

String mailBODY = "<h3>Hi this is my test Mail</h3>;

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

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

        Session session = Session.getInstance(props, new GMailAuthenticator(username, password));

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("TEST"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(test@gmail.com));
            message.setSubject("Mail subject test");
            message.setContent(mailBODY,"text/html; charset=utf-8");

            Transport.send(message);
            System.out.println("mail has been send");

        } catch (MessagingException e) {
            e.printStackTrace();
        }
4

2 回答 2

2

尝试添加道具并像这样发送:

            Properties props = System.getProperties();
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.user", from);
            props.put("mail.smtp.password", pass);
            props.put("mail.smtp.port", "587");
            props.put("mail.smtp.auth", "true");
// ...
Session session = Session.getDefaultInstance(props, null);
            MimeMessage message = new MimeMessage(session);
// ...

Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
于 2012-12-10T06:40:04.850 回答
1

我在我的谷歌帐户上启用两步验证后收到此错误

于 2014-03-29T12:00:05.470 回答