我尝试使用以下代码发送邮件,但出现异常。

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 = "[email protected]";
        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([email protected]));
            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();
        }

最佳答案

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

            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();

关于java - 如何解决javax.mail.AuthenticationFailedException?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13795704/

10-10 12:50