Using Gmail IMAP OAUTH/XOAUTH2


The Gmail IMAP and SMTP servers have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Gmail Web OAuth instead of inputting user and password directly in application. This way is more secure, but a little bit complex.

https://developers.google.com/gmail/oauth_overview?hl=en

Create your project in Google Developers Console

To use Gmail OAUTH in your application, you must create a project in Google Developers Console at first.


Use client id and client secret to get access token

You can use client id and client secret to get the user email address and access token like this:

Example

[C# - Get access token and user with Google.Apis.Auth.OAuth2]
// You can install Google.Apis.Auth.OAuth2 by NuGet
// Install-Package Google.Apis.Auth.OAuth2

using Google.Apis.Auth;
using Google.Apis.Auth.OAuth2;

var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        new ClientSecrets
        {
            ClientId = "put your client id here",
            ClientSecret = "put your client secret here"
        },
        new[] { "email", "profile", "https://mail.google.com/" },
        "user",
        CancellationToken.None
        );

var jwtPayload = GoogleJsonWebSignature.ValidateAsync(credential.Token.IdToken).Result;
var username = jwtPayload.Email;

// then you can get access token and user from the following properties
// credential.Token.AccessToken;
// username;

You should create your client id and client secret, don't use the client id in the sample project, it is only for test purpose. If you got "This app isn't verified" information, please click "advanced" -> Go to ... for test.


Use access token to retrieve email from Gmail IMAP4 server

After you get user email address and access token, you can use the following codes to retrieving email using Gmail SASL XOAUTH2 mechanism.

Example

[Visual Basic, C#, C++] The following example demonstrates how to receive email with EAGetMail POP3 & IMAP Component, but it doesn't demonstrates the events and mail parsing usage. To get the full samples of EAGetMail, please refer to Samples section.

[VB - Download email from Gmail IMAP4 server using XOAUTH2]
Imports System
Imports System.Globalization
Imports System.IO
Imports System.Text
Imports EAGetMail

Public Class TestClass
    ' Generate an unqiue email file name based on date time.
    Shared Function _generateFileName(ByVal sequence As Integer) As String
        Dim currentDateTime As DateTime = DateTime.Now
        Return String.Format("{0}-{1:000}-{2:000}.eml",
                            currentDateTime.ToString("yyyyMMddHHmmss", New CultureInfo("en-US")),
                            currentDateTime.Millisecond,
                            sequence)
    End Function
    
    Public Sub ReceiveMailByOauth(user As String, accessToken As String)

        Try
            ' Create a folder named "inbox" under current directory
            ' to save the email retrieved.
            Dim localInbox As String = String.Format("{0}\inbox", Directory.GetCurrentDirectory())

            ' If the folder is not existed, create it.
            If Not Directory.Exists(localInbox) Then
                Directory.CreateDirectory(localInbox)
            End If

            ' use SSL IMAP + XOAUTH2
            Dim oServer As New MailServer("imap.gmail.com", user, accessToken, True,
                        ServerAuthType.AuthXOAUTH2, ServerProtocol.Imap4)

            oServer.Port = 993

            Console.WriteLine("Connecting server ...")
            Dim oClient As New MailClient("TryIt")
            oClient.Connect(oServer)

            Console.WriteLine("Retrieving email list ...")
            Dim infos() As MailInfo = oClient.GetMailInfos()

            Console.WriteLine("Total {0} email(s)", infos.Length)

            For i As Integer = 0 To infos.Length - 1
                Console.WriteLine("Checking {0}/{1}", i + 1, infos.Length)
                Dim info As MailInfo = infos(i)

                ' Generate an unqiue email file name based on date time.
                Dim fileName As String = _generateFileName(i + 1)
                Dim fullPath As String = String.Format("{0}\{1}", localInbox, fileName)

                Console.WriteLine("Downloading {0}/{1}", i + 1, infos.Length)
                Dim oMail As Mail = oClient.GetMail(info)

                ' Save email to local disk
                oMail.SaveAs(fullPath, True)

                ' Mark email as deleted on server.
                Console.WriteLine("Deleting ... {0}/{1}", i + 1, infos.Length)
                oClient.Delete(info)
            Next

            Console.WriteLine("Disconnecting ...")
            ' Delete method just mark the email as deleted, 
            ' Quit method expunge the emails from server permanently.
            oClient.Quit()

            Console.WriteLine("Completed!")
        Catch ep As Exception
            Console.WriteLine("Error: {0}", ep.Message)
        End Try

    End Sub

End Class


[C# - Download email from Gmail IMAP4 server using XOAUTH2] using System; using System.IO; using System.Globalization; using System.Text; using EAGetMail; class TestClass { // Generate an unqiue email file name based on date time static string _generateFileName(int sequence) { DateTime currentDateTime = DateTime.Now; return string.Format("{0}-{1:000}-{2:000}.eml", currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")), currentDateTime.Millisecond, sequence); } public void ReceiveMailByOauth(string user, string accessToken) { try { // Create a folder named "inbox" under current directory // to save the email retrieved. string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory()); // If the folder is not existed, create it. if (!Directory.Exists(localInbox)) { Directory.CreateDirectory(localInbox); } // use SSL IMAP + XOAUTH2 MailServer oServer = new MailServer("imap.gmail.com", user, accessToken, true, ServerAuthType.AuthXOAUTH2, ServerProtocol.Imap4); oServer.Port = 993; Console.WriteLine("Connecting server ..."); MailClient oClient = new MailClient("TryIt"); oClient.Connect(oServer); Console.WriteLine("Retreiving email list ..."); MailInfo[] infos = oClient.GetMailInfos(); Console.WriteLine("Total {0} email(s)", infos.Length); for (int i = 0; i < infos.Length; i++) { Console.WriteLine("Checking {0}/{1} ...", i + 1, infos.Length); MailInfo info = infos[i]; // Generate an unqiue email file name based on date time. string fileName = _generateFileName(i + 1); string fullPath = string.Format("{0}\\{1}", localInbox, fileName); Console.WriteLine("Downloading {0}/{1} ...", i + 1, infos.Length); Mail oMail = oClient.GetMail(info); // Save mail to local file oMail.SaveAs(fullPath, true); // Mark the email as deleted on server. Console.WriteLine("Deleting ... {0}/{1}", i + 1, infos.Length); oClient.Delete(info); } Console.WriteLine("Disconnecting ..."); // Delete method just mark the email as deleted, // Quit method expunge the emails from server permanently. oClient.Quit(); Console.WriteLine("Completed!"); } catch (Exception ep) { Console.WriteLine("Error: {0}", ep.Message); } } }
[C++/CLI - Download email from Gmail IMAP4 server using XOAUTH2] using namespace System; using namespace System::Globalization; using namespace System::IO; using namespace EAGetMail; //add EAGetMail namespace // Generate an unqiue email file name based on date time static String ^ _generateFileName(int sequence) { DateTime currentDateTime = DateTime::Now; return String::Format("{0}-{1:000}-{2:000}.eml", currentDateTime.ToString("yyyyMMddHHmmss", gcnew CultureInfo("en-US")), currentDateTime.Millisecond, sequence); } void ReceiveMailByOauth(String ^user, String ^accessToken) { try { // Create a folder named "inbox" under current directory // to save the email retrieved. String ^localInbox = String::Format("{0}\\inbox", Directory::GetCurrentDirectory()); // If the folder is not existed, create it. if (!Directory::Exists(localInbox)) { Directory::CreateDirectory(localInbox); } // use SSL IMAP + XOAUTH2 MailServer ^oServer = gcnew MailServer("imap.gmail.com", user, accessToken, true, ServerAuthType::AuthXOAUTH2, ServerProtocol::Imap4); oServer->Port = 993; Console::WriteLine("Connecting server ..."); MailClient ^oClient = gcnew MailClient("TryIt"); oClient->Connect(oServer); Console::WriteLine("Retreiving email list ..."); array<MailInfo^>^infos = oClient->GetMailInfos(); Console::WriteLine("Total {0} email(s)", infos->Length); for (int i = 0; i < infos->Length; i++) { Console::WriteLine("Checking {0}/{1}", i + 1, infos->Length); MailInfo ^info = infos[i]; // Generate an unqiue email file name based on date time String^ fileName = _generateFileName(i + 1); String^ fullPath = String::Format("{0}\\{1}", localInbox, fileName); Console::WriteLine("Downloading {0}/{1}", i + 1, infos->Length); Mail ^oMail = oClient->GetMail(info); // Save email to local disk oMail->SaveAs(fullPath, true); // Mark email as deleted on server. Console::WriteLine("Deleting ... {0}/{1}", i + 1, infos->Length); oClient->Delete(info); } Console::WriteLine("Disconnecting ..."); // Delete method just mark the email as deleted, // Quit method expunge the emails from server permanently. oClient->Quit(); Console::WriteLine("Completed!"); } catch (Exception ^ep) { Console::WriteLine("Error: {0}", ep->Message); } }

Remarks

If your application is background service which doesn't support user interaction, please have a look at this topic: Use G Suite service account to do IMAP4 OAUTH.

If you don't want to use OAUTH 2.0, Gmail also supports traditional AuthLogin authentication, but you need to enable Allowing less secure apps or Sign in using App Passwords.

See Also

Using EAGetMail POP3 & IMAP4 .NET Component
User Authentication and SSL Connection
Enable TLS 1.2 on Windows XP/2003/2008/7/2008 R2
Using Gmail/GSuite Service Account + IMAP4 OAUTH
Using Office365 EWS OAUTH
Using Office365 EWS OAUTH in Background Service
Using Hotmail IMAP4 OAUTH
Digital Signature and E-mail Encryption/Decryption
Unique Identifier (UIDL) in POP3 and IMAP4 protocol
Parse Bounced Email (delivery-report)
Work with winmail.dat (TNEF Parser)
EAGetMail Namespace References
EAGetMail POP3 & IMAP4 Component Samples

Online Tutorials

C# - Retrieve Email using Google/Gmail OAuth 2.0 Authentication + IMAP Protocol
C# -Retrieve Email using Gmail/G Suite OAuth 2.0 + IMAP4 Protocol in Background Service (Service Account)
C# -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + IMAP4 Protocol from Hotmail/Outlook Account
C# -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS/IMAP4 Protocol from Office 365 Account
C# -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS Protocol from Office 365 in Background Service

VB - Retrieve Email using Google/Gmail OAuth 2.0 Authentication + IMAP Protocol
VB -Retrieve Email using Gmail/G Suite OAuth 2.0 + IMAP4 Protocol in Background Service (Service Account)
VB -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + IMAP4 Protocol from Hotmail/Outlook Account
VB -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS/IMAP4 Protocol from Office 365 Account
VB -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS Protocol from Office 365 in Background Service

C++/CLR - Retrieve Email using Google/Gmail OAuth 2.0 Authentication + IMAP Protocol
C++/CLR -Retrieve Email using Gmail/G Suite OAuth 2.0 + IMAP4 Protocol in Background Service (Service Account)
C++/CLR -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + IMAP4 Protocol from Hotmail/Outlook Account
C++/CLR -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS/IMAP4 Protocol from Office 365 Account
C++/CLR -Retrieve Email using Microsoft OAuth 2.0 (Modern Authentication) + EWS Protocol from Office 365 in Background Service