Using Gmail IMAP OAUTH


Import Notice: Because Google has disabled Google Plus Api since March 2019, current sample project won't work correctly. We will release a new version with new sample project in 30 days. If you need to use new Google XOAUTH2 with SMTP/IMAP4 service urgently, please contact support@emailarchitect.net, we can send you the new sample project within a couple days.

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.

Using Client ID and Client secret to get access token

Now you can use client id and client secret to get the user email address and access token. Basically, OAUTH uses HTTP protocol, first of all, user inputs user and password in Google Web Authentication, Google returns access token back to your application, finally your application uses access token to access Gmail IMAP server. You can find the example codes in EAGetMail Installation Path\Samples_{Programming language/Developer Tool}\GmailOAUTH.* project.

How to use access token with Gmail IMAP Service.

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++] 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 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.AuthType = MailServerAuthXOAUTH2
    
    oServer.SSLConnection = True
    oServer.Protocol = MailServerImap4
    oServer.Port = 993 'SSL IMAP4
    
    On Error GoTo ErrorHandle
        oClient.Connect oServer
        Dim infos
        infos = oClient.GetMailInfos()
        
        Dim i, Count
        Count = UBound(infos)
        For i = LBound(infos) To Count
            Dim info As EAGetMailObjLib.MailInfo
            Set info = infos(i)
            
            MsgBox "UIDL: " & info.UIDL
            MsgBox "Index: " & info.Index
            MsgBox "Size: " & info.Size
            MsgBox "Flags: " & info.IMAP4Flags 
            
            MsgBox "Read: " & info.Read
            MsgBox "Deleted: " & info.Deleted

            Dim oMail As EAGetMailObjLib.Mail
            Set oMail = oClient.GetMail(info)
            'Save mail to local
            oMail.SaveAs "d:\tempfolder\" & i & ".eml", True
        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 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.AuthType = MailServerAuthXOAUTH2
    
    oServer.SSLConnection = True
    oServer.Protocol = MailServerImap4
    
    oServer.Port = 993 'SSL IMAP4

    oClient.Connect oServer
    Dim infos
    infos = oClient.GetMailInfos()
    
    Dim i, Count
    Count = UBound(infos)
    For i = LBound(infos) To Count
        Dim info
        Set info = infos(i)
        
        MsgBox "UIDL: " & info.UIDL
        MsgBox "Index: " & info.Index
        MsgBox "Size: " & info.Size
        MsgBox "Flags: " & info.IMAP4Flags 
        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
    Next

    oClient.Quit
End Sub

[Visual C++]
#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 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->AuthType = MailServerAuthXOAUTH2;
        
        oServer->Protocol = MailServerImap4;
       
        oServer->Port = 993;
        oServer->SSLConnection = VARIANT_TRUE;
           

        oClient->Connect( oServer );

        _variant_t arInfo = oClient->GetMailInfos();
        SAFEARRAY *psa = arInfo.parray;

        long LBound = 0, UBound = 0;
        SafeArrayGetLBound( psa, 1, &LBound );
        SafeArrayGetUBound( psa, 1, &UBound );
    
        INT count = UBound-LBound+1;
        for( long i = LBound; i <= UBound; i++ )
        {
            _variant_t vtInfo;
            SafeArrayGetElement( psa, &i, &vtInfo );
            
            IMailInfoPtr pInfo;
            vtInfo.pdispVal->QueryInterface(__uuidof(IMailInfo), (void**)&pInfo);

            _tprintf( _T("UIDL: %s\r\n"), (TCHAR*)pInfo->UIDL );
            _tprintf( _T("Index: %d\r\n"), (TCHAR*)pInfo->Index);
            _tprintf( _T("Size: %d\r\n"), (TCHAR*)pInfo->Size);
            _tprintf( _T("Flags: %s\r\n"), (TCHAR*)pInfo->IMAP4Flags );
            _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();
        }

        oClient->Quit();
    }
    catch( _com_error &ep )
    {
        _tprintf( _T("ERROR: %s\r\n"),  (TCHAR*)ep.Description());
    }

    ::CoUninitialize();
}

Remarks

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
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

Read Email over SSL/TLS Connection in Delphi - Tutorial
Read Email from Gmail Account in Delphi - Tutorial
Read Email from Yahoo Account in Delphi - Tutorial
Read Email from Hotmail Account in Delphi - Tutorial

Read Email over SSL/TLS Connection in VB6 - Tutorial
Read Email from Gmail Account in VB6 - Tutorial
Read Email from Yahoo Account in VB6 - Tutorial
Read Email from Hotmail Account in VB6 - Tutorial

Read Email over SSL/TLS Connection VC++ - Tutorial
Read Email from Gmail Account in VC++ - Tutorial
Read Email from Yahoo Account in VC++ - Tutorial
Read Email from Hotmail Account in VC++ - Tutorial