Skip to content

Latest commit

 

History

History
97 lines (62 loc) · 4.37 KB

GMailOAuth2.md

File metadata and controls

97 lines (62 loc) · 4.37 KB

Using OAuth2 With GMail (IMAP, POP3 or SMTP)

Quick Index

Setting up OAuth2 for use with Google Mail

Register Your Application with Google

Go to Google's Developer Console.

Click the Select A Project button in the Navigation Bar at the top of the screen.

Click "Select A Project"

Click the New Project button.

Click "New Project"

Fill in the name Project Name, and if appropriate, select the Organization that your program should be associated with. Then click Create.

Create New Project

Obtaining an OAuth2 Client ID and Secret

Click the symbol, move down to APIs & Services and then select OAuth consent screen.

Click "OAuth consent screen"

Select the External radio item and then click Create.

Select "External"

Fill in the Application name and any other fields that are appropriate for your application and then click Create.

OAuth consent screen

Click + Create Credentials and then select OAuth client ID.

Click "Create Credentials"

Select the Other radio item in the Application type section and then type in a name to use for the OAuth client ID. Once completed, click Create.

Select "Other"

At this point, you will be presented with a web dialog that will allow you to copy the Client ID and Client Secret strings into your clipboard to paste them into your program.

Client ID and Secret

Authenticating with the OAuth2 Client ID and Secret

Now that you have the Client ID and Client Secret strings, you'll need to plug those values into your application.

The following sample code uses the Google.Apis.Auth nuget package for obtaining the access token which will be needed by MailKit to pass on to the GMail server.

const string GMailAccount = "[email protected]";

var clientSecrets = new ClientSecrets {
	ClientId = "XXX.apps.googleusercontent.com",
	ClientSecret = "XXX"
};

var codeFlow = new GoogleAuthorizationCodeFlow (new GoogleAuthorizationCodeFlow.Initializer {
	DataStore = new FileDataStore ("CredentialCacheFolder", false),
	Scopes = new [] { "https://mail.google.com/" },
	ClientSecrets = clientSecrets
});

// Note: For a web app, you'll want to use AuthorizationCodeWebApp instead.
var codeReceiver = new LocalServerCodeReceiver ();
var authCode = new AuthorizationCodeInstalledApp (codeFlow, codeReceiver);

var credential = await authCode.AuthorizeAsync (GMailAccount, CancellationToken.None);

if (credential.Token.IsExpired (SystemClock.Default))
	await credential.RefreshTokenAsync (CancellationToken.None);

var oauth2 = new SaslMechanismOAuth2 (credential.UserId, credential.Token.AccessToken);

using (var client = new ImapClient ()) {
	await client.ConnectAsync ("imap.gmail.com", 993, SecureSocketOptions.SslOnConnect);
	await client.AuthenticateAsync (oauth2);
	await client.DisconnectAsync (true);
}