SMTP and OAuth 2

17,876

Solution 1

System.Net.Mail does not support OAuth or OAuth2. However, you can use MailKit's (note: only supports OAuth2) SmtpClient to send messages as long as you have the user's OAuth access token (MailKit does not have code that will fetch the OAuth token, but it can use it if you have it).

The first thing you need to do is follow Google's instructions for obtaining OAuth 2.0 credentials for your application.

Once you've done that, the easiest way to obtain an access token is to use Google's Google.Apis.Auth library:

var certificate = new X509Certificate2 (@"C:\path\to\certificate.p12", "password", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential (new ServiceAccountCredential
    .Initializer ("[email protected]") {
    // Note: other scopes can be found here: https://developers.google.com/gmail/api/auth/scopes
    Scopes = new[] { "https://mail.google.com/" },
    User = "[email protected]"
}.FromCertificate (certificate));

bool result = await credential.RequestAccessTokenAsync (CancellationToken.None);

// Note: result will be true if the access token was received successfully

Now that you have an access token (credential.Token.AccessToken), you can use it with MailKit as if it were the password:

using (var client = new SmtpClient ()) {
    client.Connect ("smtp.gmail.com", 587, SecureSocketOptions.StartTls);

    // use the access token
    var oauth2 = new SaslMechanismOAuth2 ("[email protected]", credential.Token.AccessToken);
    client.Authenticate (oauth2);

    client.Send (message);

    client.Disconnect (true);
}

Solution 2

Just adding to the above answer. I also spend lot of time to find out things for sending email using gmail oAuth2 with mailkit in .net. As I am using this to send email to my App users. Thanks to mailkit developers.

Now we need:

  • Authorization code
  • Client ID
  • Client Secret
  • Refresh Token
  • Access Token

You can directly get the Client Id and Client Secret from google console by creating your project.

Next you can enable gmail app from the Google Developers OAuth Playground by using your own OAuth credentials in left top setting button.

After that Select and Authorize the API https://mail.google.com/.

Now you can directly refresh token by this http POST request https://developers.google.com/oauthplayground/refreshAccessToken. you will find the parameter in there.

Now you can directly use this code in your C# code using MailKit:

using (var client = new SmtpClient())
{
    client.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
    
    var oauth2 = new SaslMechanismOAuth2(GMailAccount, token.AccessToken);
    client.Authenticate(oauth2);
    
    await client.SendAsync(mailMessage);
    client.Disconnect(true);
}

Now you will be able to send email through your gmail account from server side.

Share:
17,876
user3288287
Author by

user3288287

Updated on June 15, 2022

Comments

  • user3288287
    user3288287 almost 2 years

    Does .NET support SMTP authentication via OAuth protocol? Basically, I would like to be able to send emails on users' behalves using OAuth access tokens. However, I couldn't find a support for this in the .NET framework.

    Google provides some samples for this in other environments but not .NET.