在 Mailkit 中使用 Google OAuth 时需要身份验证错误

Authentication Required error when using Google OAuth in Mailkit

我正尝试在 mailkit 中使用 Google OAuth 从我的应用程序发送邮件。

使用 Google Auth .net 库,我从 Google 获得了用户的访问令牌。当我使用 mailkit 中的访问令牌发送电子邮件时,如下所示,

var SocketOption = SecureSocketOptions.StartTls;

await smtpClient.ConnectAsync(smtp.gmail.com, 587, SocketOption).ConfigureAwait(false);

await smtpClient.AuthenticateAsync(userid, accesstoken).ConfigureAwait(false);

await smtpClient.SendAsync(message).ConfigureAwait(false);

我从 Mailkit 收到以下异常。

MailKit.ServiceNotAuthenticatedException: '5.7.0 Authentication Required. Learn more at 5.7.0 https://support.google.com/mail/?p=WantAuthError f23sm12136220pfa.85 - gsmtp'

注意: 我确认我从 Google 收到的访问令牌是有效的,通过将它与 Gmail API 一起使用,如下所示。

var gmailService = new Google.Apis.Gmail.v1.GmailService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = "App name"
            });

var gmailProfile = gmailService.Users.GetProfile("me").Execute();
string EmailAddress = gmailProfile.EmailAddress;

所以,我使用的凭据不是问题。

如果您要通过 OAuth2 进行身份验证,则需要明确使用 OAuth2 SASL 机制:

var sasl = new SaslMechanismOAuth2 (userid, accesstoken);
await smtpClient.AuthenticateAsync(sasl).ConfigureAwait(false);