1

我正在尝试通过使用 oAuth2 机制连接到 Google SMTP 服务器来发送邮件。

public static Transport connectToSmtp(String smtpServer, int port, String email, String authToken, boolean isDebug, MimeMessage mimeMsg)
     throws Exception
{
    Properties props = new Properties();
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.starttls.required", "true");
    props.put("mail.smtp.sasl.enable", "true");
    props.put("mail.smtp.sasl.mechanisms", "XOAUTH2");
    props.put("mail.imaps.sasl.mechanisms.oauth2.oauthToken", authToken);
    Session session = Session.getInstance(props);
    session.setDebug(isDebug);
    final String emptyPassword = "";
    Transport transport = session.getTransport("smtp");
    transport.connect(smtpServer, port, email, emptyPassword);
    try
    {
        transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());
    }
    catch (Exception e)
    {
        logger.log(Level.WARNING, "Exception Occured : ", e);
    }
    return transport;
}

我的应用程序的客户端 ID 和密钥:

ID - 345101*-i6ki*4tk1sms.apps.googleusercontent.com

秘密 - e6NHB*- eZ-r k

上面的代码抛出了以下错误:

javax.mail.AuthenticationFailedException:535-5.7.8 用户名和密码不被接受。了解更多信息,请访问 535 5.7.8 https://support.google.com/mail/answer/14257 o135sm276925ith.4 - gsmtp

SMTP 服务器:aspmx.l.google.com,端口:25

编辑:

我为我尝试连接的 Google App 帐户更改了以下内容,并且清除了上述异常:

  1. 没有两步验证

  2. 允许安全性较低的应用程序“安全”->“基本设置”->“转到安全性较低的应用程序的设置”->“允许用户管理他们对安全性较低的应用程序的访问”

但是在清除了上述异常之后。我有另一个例外。

com.sun.mail.smtp.SMTPSendFailedException:550-5.7.1 中继凭据无效 [121. . .2]。您在 Google Apps SMTP 中继服务中注册的 IP 地址与发送此电子邮件的帐户的域不匹配。如果您尝试中继来自未在您的 Googles Apps 帐户下注册的域或具有空信封的域的邮件,则必须将您的邮件服务器配置为使用 SMTP AUTH 来识别发送域或显示您的域之一HELO 或 EHLO 命令中的名称。欲了解更多信息,请访问 https://support.google.com/a/answer/6140680#invalidcred f65sm341248ith.1 - gsmtp;

所以我更改了以下设置:

应用程序 > Google Apps > Gmail > Gmail 设置 > 高级设置

SMTP 中继服务

  • 允许的发件人:任何地址(不推荐)
  • 只接受来自指定 IP 地址的邮件:否
  • 需要 SMTP 身份验证:是
  • 需要 TLS 加密:否

即使在尝试上述更改后,也会引发相同的异常。请帮忙。

4

1 回答 1

1

在将实际邮件数据发送到 SMTP 服务器的传输对象中,必须区分普通身份验证和 OAuth2 。这是在 JavaMail 中使用Transport.connect()中的密码参数完成的。

如果在上述代码中密码为null,则 Java MailClient 将身份验证视为 OAuth 而不是普通身份验证。

所以代码应该是

final String emptyPassword = null;

作为对评论的回复,
如果身份验证是作为 IP 地址给出的,则不验证给定的用户名和密码。相反,连接来自的 IP 地址用作身份验证。
这就是相同代码起作用的原因,当您将发件人 IP 地址添加到 GApps 中继邮件设置并选择身份验证类型作为 IP 地址时。

于 2017-01-24T07:19:54.157 回答