SMTP Google 应用程序 Oauth2 - 中继问题

SMTP Google Apps Oauth2 - issue in relay

我正在尝试通过使用 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-rk

以上代码抛出以下错误:

javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8 https://support.google.com/mail/answer/14257 o135sm276925ith.4 - gsmtp

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

已编辑:

我已经为我正在尝试连接的 Google 应用程序帐户更改了以下内容,并且清除了上述异常:

  1. 无两步验证

  2. 允许安全性较低的应用程序 "Security" -> "Basic Settings" -> "Go to settings for less secure apps" -> "Allow Users to Manager Their Access to Less Secure Apps"

但是在清除上面的异常之后。我又遇到了一个例外。

com.sun.mail.smtp.SMTPSendFailedException: 550-5.7.1 Invalid credentials for relay [121...2]. The IP address you've registered in Google Apps SMTP Relay service doesn't match domain of the account this email is being sent from. If you are trying to relay mail from a domain that isn't registered under your Googles Apps account or has empty envelope-from, you must configure your mail server either to use SMTP AUTH to identify the sending domain or to present one of your domain names in the HELO or EHLO command. For more information, please visit https://support.google.com/a/answer/6140680#invalidcred f65sm341248ith.1 - gsmtp ;

所以我更改了以下设置:

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

SMTP 中继服务

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

普通身份验证和 OAuth2 必须在 Transport 对象中加以区分,后者将实际邮件数据发送到 SMTP 服务器。 这是在 JavaMail 中使用 Transport.connect().

中的密码参数完成的

如果密码在上面的代码中被指定为 null,那么 Java MailClient 会将身份验证视为 OAuth 而不是普通身份验证。

所以代码应该是

final String emptyPassword = null;

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