【问题标题】:Send mail using Gmail from Java without turning on less secure app使用 Java 中的 Gmail 发送邮件,而无需打开不太安全的应用程序
【发布时间】:2017-09-30 10:21:36
【问题描述】:

我正在尝试使用 Java 向 Gmail 帐户发送邮件,代码如下。我似乎做的一切都是正确的,但是我收到了身份验证失败。 Google 希望我打开“不太安全的应用”功能以启用传输。

有没有一种方法可以让 Gmail 对 Java 感到满意并且不会抛出“打开不太安全的应用程序”错误?

错误:

javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=...U
534-5.7.14 FigguJaZwDtp...
534-5.7.14 ...o> Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14  Learn more at
534 5.7.14  https://support.google.com/mail/answer/... - gsmtp

代码:

String hostSmtpUser = "myemail@gmail.com";
String host = "smtp.gmail.com";
String hostPort = "587";
String hostSmtpPassword = "thepassword";

Properties properties = System.getProperties();
properties.setProperty("mail.smtp.user", hostSmtpUser);
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.port", hostPort);
properties.setProperty("mail.smtp.auth", "true");

Session oSession;
if (true == ToolsCommon.isEmpty(hostSmtpUser))
    oSession = Session.getInstance(properties);
else
    oSession = Session.getInstance(properties, new javax.mail.Authenticator()
    {
        protected PasswordAuthentication getPasswordAuthentication()
        {
        return new PasswordAuthentication(hostSmtpUser, hostSmtpPassword);
        }
    });

// Compose the message  
try
{
    MimeMessage message = new MimeMessage(oSession);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(Subject);
    message.setText(Body);

    // Send message  
    Transport.send(message);
}

catch (MessagingException ex)
{
    // Log the error.
    ToolsLog.logError(TypeLog.ui, ex);
}

我已经进行了研究,所以据我所知,代码不是问题,只是没有看到不太安全的应用消息的解决方法。

参考资料:

Ref 1 Ref 2 Ref 3 Ref 4

【问题讨论】:

    标签: java email smtp gmail


    【解决方案1】:

    默认情况下,GMail 不允许基于密码的身份验证 - 这就是为什么您必须允许“不太安全的应用程序”按原样使用您的程序。

    相反,您可以use OAuth 2.0 避免直接使用密码。该方法被 Google 认为是安全的,不需要更改任何帐户设置。

    【讨论】:

      猜你喜欢
      • 2020-01-07
      • 2020-04-17
      • 2016-06-03
      • 2020-05-30
      • 2013-11-11
      • 2015-02-19
      • 2022-07-19
      • 2016-11-06
      • 2019-01-19
      相关资源
      最近更新 更多