首页 > 解决方案 > 异常:javax.mail.AuthenticationFailedException:连接失败,没有指定密码?即使使用 PasswordAuthenticator?

问题描述

我正在制作一个发送电子邮件的 java 应用程序。

出于某种原因,javax.mail.AuthenticationFailedException即使我有正确的用户名和密码,我也不断收到 。

我看过一些帖子说缺少密码身份验证也可能导致此异常,但我认为我也有这部分。现在我被困住了,无法弄清楚哪里出了问题。

这是我的代码:

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import javax.swing.*;

public class sendEmail {
    private static String subject = "Test", content = "This is a test";

    public sendEmail() {

    }

    public static void send() throws MessagingException{
        Properties properties = new Properties();
        properties.put("mail.smtp.auth","true");// set the authentication to true
        properties.put("mail.smtp.starttls.enable","true");
        properties.put("mail.smtp.host","smtp.gmail.com");
        properties.put("mail.smtp.port","587");
        String username = "clashroyale70532@gmail.com";
        String password = "********";
        Session ses = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPassWordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        ses.setDebug(true);
        Message message = prepareMessage(ses,username);
        Transport.send(message);
    }

    private static Message prepareMessage(Session session, String account) {
        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(account));
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(account));
            msg.setSubject(subject);
            msg.setText(content);
            return msg;
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException m) {
            throw new RuntimeException(m);
        }
        return null;
    }
    public static void main(String[] args) {
        try {
            sendEmail.send();
            }
            catch (MessagingException m) {
                m.printStackTrace();
            }
    }

}

这是 JavaMail 调试输出:

 DEBUG: setDebug: JavaMail version 1.6.2
    DEBUG: getProvider() returning 
    javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
    DEBUG SMTP: need username and password for authentication
    DEBUG SMTP: protocolConnect returning false, host=smtp.gmail.com, user=*******(name not shown, it's my real name), password=<null>

它显示的用户与我在代码中使用的电子邮件帐户没有关联。我不确定它是如何得到我的真名的。

标签: javajakarta-mail

解决方案


推荐阅读