Authenticating with IMAP and SMTP using XOAuth2

This article shows how to authenticate with IMAP and SMTP using XOAuth2.

Date Entered: 10/23/2014    Last Updated: 01/03/2020

Some environments may require authentication using XOAuth2 when connecting via IMAP and SMTP. An example of this is Gmail if the account is configured to restrict access to secure apps. Instead of enabling connections for less secure apps the OAuth component can be used to obtain an authorization string for use with XOAuth2 in IMAP or SMTP.

The OAuth component provides an easy way to obtain an authorization string for future requests to a service. The component implements an OAuth 2.0 client.

You still need a username for the OAuth component but you don't need to supply a password.

  1. Authenticating with IMAP
  2. //Setting Gmail server settings imap1.MailServer = "imap.gmail.com"; imap1.User = "youraddress@gmail.com"; imap1.SSLStartMode = IPWorks.ImapSSLStartModes.sslImplicit; imap1.MailPort = 993; //Getting an authorization string oauth1.ClientId = "723966830965.apps.googleusercontent.com"; oauth1.ClientSecret = "_bYMDLuvYkJeT_99Q-vkP1rh"; oauth1.ServerAuthURL = "https://accounts.google.com/o/oauth2/auth"; oauth1.ServerTokenURL = "https://accounts.google.com/o/oauth2/token"; oauth1.AuthorizationScope = "https://mail.google.com/"; string authorization = oauth1.GetAuthorization(); //Authenticating using XOAuth2 imap1.AuthMechanism = IPWorks.ImapAuthMechanisms.amXOAUTH2; imap1.Config("AuthorizationIdentity=" + authorization); imap1.Connect(); //Additional code here imap1.Disconnect(); MessageBox.Show("Connected.", "IMAP", MessageBoxButtons.OK);
  3. Authenticating with SMTP
  4. //Setting Gmail server settings htmlmailer1.MailServer = "smtp.gmail.com"; htmlmailer1.SendTo = "sendto@email.com"; htmlmailer1.Subject = "Testing OAuth"; htmlmailer1.From = "youraddress@gmail.com"; htmlmailer1.User = "youraddress@gmail.com"; //Getting an authorization string oauth1.ClientId = "723966830965.apps.googleusercontent.com"; oauth1.ClientSecret = "_bYMDLuvYkJeT_99Q-vkP1rh"; oauth1.ServerAuthURL = "https://accounts.google.com/o/oauth2/auth"; oauth1.ServerTokenURL = "https://accounts.google.com/o/oauth2/token"; oauth1.AuthorizationScope = "https://mail.google.com/"; string authorization = oauth1.GetAuthorization(); //Authenticating using XOAuth2 htmlmailer1.AuthMechanism = IPWorks.HtmlmailerAuthMechanisms.amXOAUTH2; htmlmailer1.Config("AuthorizationIdentity=" + authorization); htmlmailer1.MessageHTML = "

    Test Mail

    "; htmlmailer1.Connect(); htmlmailer1.Send(); htmlmailer1.Disconnect(); MessageBox.Show("Message Sent.", "HTMLMailer", MessageBoxButtons.OK);

We appreciate your feedback.  If you have any questions, comments, or suggestions about this entry please contact our support team at kb@nsoftware.com.