java - 使用 Java 通过 Gmail 发送的问题

标签 java email authentication gmail

我有看似非常简单的代码,可以尝试使用我的 Gmail 帐户从我的 Java 应用程序发送电子邮件。当我运行它时,它崩溃并出现异常 javax.mail.AuthenticationFailedException。这是代码:

    // Recipient's email ID needs to be mentioned.
    String to = "fredxya@gmail.com";

    // Sender's email ID needs to be mentioned
    String from = "johnxyzn@gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("fredxyz@gmail.com","password");
            }
        });

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

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

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

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

        // Now set the actual message
        message.setText("this is a test");

        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    }catch (MessagingException mex) {
        System.out.println (mex) ;
        mex.printStackTrace();
    }

最佳答案

问题是我在 Gmail 中使用了两步验证。解决方案是使用应用程序特定密码 (ASP):https://accounts.google.com/IssuedAuthSubTokens?hide_authsub=1

关于java - 使用 Java 通过 Gmail 发送的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29375551/

相关文章:

java - 试图了解 CascadeType.ALL 与 @OnDelete 的区别!

java - 强制 Tomcat 通过 http 使用安全的 JSESSIONID cookie

python - OpenID 登录不太有效

java - Android:下载受 NTLM 身份验证保护的文件

c# - ASP.NET MVC 中的自定义安全方案

java - 在 OS/X 上用 Java 打开文件

excel - 如何在电子邮件中找到国家/地区缩写

php - php发送的电子邮件中的Message-Id有什么问题

email - CentOS、mod_evasive 日志写入权限和电子邮件问题

java - 为什么我制作的 Basic Java Hex Editor 会卡住大约 2MB 大小或更大的文件?