Discuss this help topic in SecureBlackbox Forum

SMTP: Login to the server using OAuth2

Login using OAuth2 tokens can be different from server to server. We'll review the GMail case.

The simplest way to login to GMail SMTP server is to use TElSimpleOAuth2Client class. The following code snippet shows how to have this task done.


// create an HTTPS client; it's required to contact the authorization server
TElHTTPSClient https = new TElHTTPSClient();
// assign an event handler to validate SSL certificate(s)
https.OnCertificateValidate += ...;

// create a OAuth 2.0 client
TElSimpleOAuth2Client oauth = new TElSimpleOAuth2Client();
// assign the created HTTPS transport
oauth.HTTPClient = https;
// set the local URL to be used during authorization;
// the specified port must be free and the program
// has to be allowed to open a listening socket on that port
oauth.RedirectURL = @"http://localhost:5050/";
// the event is fired when it's needed to open a web page in a browser
oauth.OnLaunchBrowser += delegate (object Sender, string URL)
// authorization server URLs
oauth.AuthURL = @"https://accounts.google.com/o/oauth2/auth";
oauth.TokenURL = @"https://accounts.google.com/o/oauth2/token";

// copy client id and client secret from Google Developers Console
oauth.ClientID = @"your_client_id";
oauth.ClientSecret = @"your_client_secret";
// tell the authorization server what access is needed
oauth.Scope = @"https://mail.google.com/";

// restore the refresh token from the previous session;
// this allows to not ask the user to login in the browser each time
oauth.RefreshToken = @"refresh_token_string";

// actually, perform the authorization
if (!oauth.Authorize())
    return;    // the user has cancelled authorization

// itís a good idea to save the refresh token for future use
Console.WriteLine("RefreshToken: " + oauth.RefreshToken);
// create an SMTP client
TElSMTPClient smtp = new TElSMTPClient();

// configure it to connect to Google POP3 server
smtp.Address = "smtp.gmail.com";
smtp.Port = 587;
smtp.SSLMode = SBSSLCommon.TSBSSLMode.smExplicit;
smtp.UseSSL = true;
// assign an event handler to validate SSL certificate(s)
smtp.OnCertificateValidate += ...;

// connect to the server

// enable the necessary mechanism
smtp.set_SASLMechanism("XOAUTH2", true);
smtp.set_SASLMechanismPriorities("XOAUTH2", 1000);

// username must be the same as the one used to login in the browser
smtp.Username = "cooluser";
// use access token as the password
smtp.Password = oauth.AccessToken;

// actually, login to the server

How To articles about SMTP client

Discuss this help topic in SecureBlackbox Forum