SMTP and OAuth 2

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

Leave a Comment