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:

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 retrieve email using Gmail SASL XOAUTH2 mechanism.

Example

[Visual Basic 6.0, VBScript, Visual C++, Delphi] The following example demonstrates how to receive email using Gmail IMAP OAUTH, but it doesn't demonstrates the events and mail parsing usage. To get the full samples of EAGetMail, please refer to Samples section.

[Visual Basic 6.0]
Public Sub ReceiveMail( _
ByVal userEmail As String, _
ByVal accessToken As String)
    
    Const MailServerPop3 = 0
    Const MailServerImap4 = 1
    Const MailServerEWS = 2
    Const MailServerDAV = 3
    Const MailServerMsGraph = 4

    Const MailServerAuthLogin = 0
    Const MailServerAuthCRAM5 = 1
    Const MailServerAuthNTLM = 2
    Const MailServerAuthXOAUTH2 = 3
    
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"
    
    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "imap.gmail.com"
    oServer.User = userEmail
    oServer.Password = accessToken
    oServer.Protocol = MailServerImap4
    oServer.AuthType = MailServerAuthXOAUTH2
    
    oServer.SSLConnection = True
    oServer.Port = 993 'SSL IMAP4
    
    On Error GoTo ErrorHandle
        oClient.Connect oServer

        Dim infos
        Set infos = oClient.GetMailInfoList()
        
        Dim i
        For i = 0 To infos.Count - 1
            Dim info
            Set info = infos.Item(i)
            
            MsgBox "UIDL: " & info.UIDL
            MsgBox "Index: " & info.Index
            MsgBox "Size: " & info.Size

            MsgBox "Read: " & info.Read
            MsgBox "Deleted: " & info.Deleted
                        
            Dim oMail
            Set oMail = oClient.GetMail(info)
            'Save mail to local
            oMail.SaveAs "d:\tempfolder\" & i & ".eml", True

            ' Delete email from server
            oClient.Delete info
        Next

        oClient.Quit
        Exit Sub
ErrorHandle:
        ''Error handle
        MsgBox Err.Description
        
        oClient.Close
End Sub


[VBScript] Sub ReceiveMail( _ ByVal userEmail, _ ByVal accessToken) Const MailServerPop3 = 0 Const MailServerImap4 = 1 Const MailServerEWS = 2 Const MailServerDAV = 3 Const MailServerMsGraph = 4 Const MailServerAuthLogin = 0 Const MailServerAuthCRAM5 = 1 Const MailServerAuthNTLM = 2 Const MailServerAuthXOAUTH2 = 3 Dim oClient Set oClient = CreateObject("EAGetMailObj.MailClient") oClient.LicenseCode = "TryIt" Dim oServer Set oServer = CreateObject("EAGetMailObj.MailServer") oServer.Server = "imap.gmail.com" oServer.User = userEmail oServer.Password = accessToken oServer.Protocol = MailServerImap4 oServer.AuthType = MailServerAuthXOAUTH2 oServer.SSLConnection = True oServer.Port = 993 'SSL IMAP4 oClient.Connect oServer Dim infos Set infos = oClient.GetMailInfoList() Dim i For i = 0 To infos.Count - 1 Dim info Set info = infos.Item(i) MsgBox "UIDL: " & info.UIDL MsgBox "Index: " & info.Index MsgBox "Size: " & info.Size MsgBox "Read: " & info.Read MsgBox "Deleted: " & info.Deleted Dim oMail Set oMail = oClient.GetMail(info) 'Save mail to local oMail.SaveAs "d:\tempfolder\" & i & ".eml", True ' Delete email from server oClient.Delete info Next oClient.Quit End Sub
[Visual C++] #include "stdafx.h" #include <windows.h> #include "eagetmailobj.tlh" using namespace EAGetMailObjLib; void ReceiveMail( LPCTSTR userEmail, LPCTSTR accessToken) { ::CoInitialize(NULL); const int MailServerPop3 = 0; const int MailServerImap4 = 1; const int MailServerEWS = 2; const int MailServerDAV = 3; const int MailServerMsGraph = 4; const int MailServerAuthLogin = 0; const int MailServerAuthCRAM5 = 1; const int MailServerAuthNTLM = 2; const int MailServerAuthXOAUTH2 = 3; try { IMailClientPtr oClient; oClient.CreateInstance(__uuidof(EAGetMailObjLib::MailClient)); IMailServerPtr oServer; oServer.CreateInstance(__uuidof(EAGetMailObjLib::MailServer)); oClient->LicenseCode = _T("TryIt"); oServer->Server = _T("imap.gmail.com"); oServer->User = userEmail; oServer->Password = accessToken; oServer->Protocol = MailServerImap4; oServer->AuthType = MailServerAuthXOAUTH2; oServer->SSLConnection = VARIANT_TRUE; oServer->Port = 993; oClient->Connect(oServer); IMailInfoCollectionPtr infos = oClient->GetMailInfoList(); for(long i = 0; i < infos->Count; i++) { IMailInfoPtr pInfo = infos->GetItem(i); _tprintf(_T("UIDL: %s\r\n"), (TCHAR*)pInfo->UIDL); _tprintf(_T("Index: %d\r\n"), pInfo->Index); _tprintf(_T("Size: %d\r\n"), pInfo->Size); _tprintf(_T("Read: %s\r\n"), (pInfo->Read == VARIANT_TRUE)?_T("TRUE"):_T("FALSE")); _tprintf(_T("Deleted: %s\r\n"), (pInfo->Deleted == VARIANT_TRUE)?_T("TRUE"):_T("FALSE")); IMailPtr oMail = oClient->GetMail(pInfo); TCHAR szFile[MAX_PATH+1]; memset(szFile, 0, sizeof(szFile)); ::wsprintf(szFile, _T("d:\\tempfolder\\%d.eml"), i); //save to local disk oMail->SaveAs(szFile, VARIANT_TRUE); oMail.Release(); // delete email from server oClient->Delete(pInfo); } oClient->Quit(); } catch(_com_error &ep) { _tprintf(_T("ERROR: %s\r\n"), (TCHAR*)ep.Description()); } ::CoUninitialize(); }
[Delphi] const MailServerPop3 = 0; MailServerImap4 = 1; MailServerEWS = 2; MailServerDAV = 3; // Auth type MailServerAuthLogin = 0; MailServerAuthCRAM5 = 1; MailServerAuthNTLM = 2; MailServerAuthXOAUTH2 = 3; var Form1: TForm1; implementation {$R *.dfm} procedure ReceiveMail(userEmail: WideString; accessToken: WideString); var oServer: TMailServer; oClient: TMailClient; oTools: TTools; oMail: IMail; infos: IMailInfoCollection; oInfo: IMailInfo; localInbox, fileName: WideString; i: Integer; begin try // set current thread code page to system default code page. SetThreadLocale(GetSystemDefaultLCID()); oTools := TTools.Create(Application); // Create a folder named "inbox" under // current directory to store the email files localInbox := GetCurrentDir() + '\inbox'; oTools.CreateFolder(localInbox); oServer := TMailServer.Create(Application); oServer.Server := 'imap.gmail.com'; oServer.User := userEmail; oServer.Password := accessToken; oServer.Protocol := MailServerImap4; oServer.AuthType := MailServerAuthXOAUTH2; // Enable SSL Connection oServer.SSLConnection := true; oServer.Port := 993; oClient := TMailClient.Create(Application); oClient.LicenseCode := 'TryIt'; oClient.Connect1(oServer.DefaultInterface); ShowMessage('Connected!'); infos := oClient.GetMailInfoList(); ShowMessage(Format('Total %d email(s)', [infos.Count])); for i := 0 to infos.Count - 1 do begin oInfo := infos.Item[i]; ShowMessage(Format('Index: %d; Size: %d; UIDL: ' + oInfo.UIDL, [oInfo.Index, oInfo.Size])); // Generate a random file name by current local datetime, // You can use your method to generate the filename if you do not like it fileName := localInbox + '\' + oTools.GenFileName(i) + '.eml'; // Receive email from IMAP server oMail := oClient.GetMail(oInfo); ShowMessage('From: ' + oMail.From.Address + #13#10 + 'Subject: ' + oMail.Subject); // Save email to local disk oMail.SaveAs(fileName, true); // Mark email as deleted from IMAP server oClient.Delete(oInfo); end; // Quit and expunge emails marked as deleted from IMAP server oClient.Quit; except on ep:Exception do ShowMessage('Error: ' + ep.Message); end; end; end.

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 ActiveX Object
Registration-free COM with Manifest File
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 ActiveX Object References
EAGetMail POP3 & IMAP4 Component Samples

Online Tutorials

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

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

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