Search code examples
c#.netsmtpgoogle-oauthmailkit

Authentication Required error when using Google OAuth in Mailkit


I'm trying to use Google OAuth in mailkit to send a mail from my application.

Using Google Auth .net library, I've got the access token for the user from Google. When I used the access token in mailkit to send email as below,

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);

I got the following exception from Mailkit.

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

Note: I confirmed that access token I received from Google is valid by using it with Gmail API as below.

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;

So, credential I'm using is not the problem.


Solution

  • If you are going to authenticate via OAuth2, you need to explicitly use the OAuth2 SASL mechanism:

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