VB6/ASP - Retrieve email using Google/Gmail OAuth 2.0 authentication + IMAP protocol

By default, you need to enable ” Allowing less secure apps” in Gmail, then you can retrieve email with user/password IMAP4 authentication.

However Google will disable traditional user authentication in the future, switching to Google OAuth is strongly recommended now.

Installation

Before you can use the following sample codes, you should download the EAGetMail Installer and install it on your machine at first. Full sample projects are included in this installer.

Add reference

To use EAGetMail POP3 & IMAP4 ActiveX Object in your project, the first step is Add reference of EAGetMail to your project. Please go to menu -> Project -> References -> and select EAGetMailObj ActiveX Object, click OK, the reference will be added to your project, and you can start to use it to retrieve email and parse email in your project.

add reference in VB6

Add reference in VBA (EXCEL/Access/Outlook)

Open VBA IDE by press Alt+F11, Please select menu -> Tools -> References -> and select EASendMailObj ActiveX Object, click OK, the reference will be added to current VBA project, and you can start to use it to retrieve email and parse email in your VBA project.

To better demonstrate how to retrieve email and parse email, let’s create a VB 6.0 Standard EXE project at first, then add a CommandButton on the Form, double-click this button. It is like this

VB 6.0 standard project

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 Google Web Login instead of inputting user and password directly in application.

Create project in Google Developers Console

To retrieve email using Gmail OAuth in your application, you should create a project in the Google Cloud console, go to Menu menu > IAM & Admin > Create a Project:

create new project in google cloud console
  • In the Project Name field, enter a descriptive name for your project.
  • In the Location field, click Browse to display potential locations for your project. Then, click Select.
  • After the project is created, select it from projects list as current project.
select project in google developers console

Create credentials (OAuth client id)

  • Click APIs & Services -> Dashboard -> Credentials
google oauth Credentials
  • Click Credentials -> Create Credentials -> OAuth client ID -> Web application or Other (Desktop Application). It depends on your application type.
google oauth Credentials
  • Input a name for your application, input your web applicaton url to receive authorization code at Authorized Redirect URIs. Desktop Application doesn’t require this step.
  • Click "Create", you will get client id and client secret, download and save them for later use.
google oauth client secret

Enable Gmail API

  • Enable Gmail API in "Library" -> Search "Gmail", then click "Gmail API" and enable it.
enable Gmail API

Edit scopes

  • Now you need to edit the API scopes for your project at "OAuth consent screen" -> "Edit App".
  • Add .../auth/userinfo.email, .../auth/userinfo.profile, openid and https://mail.google.com/ scopes in OAuth consent screen -> Edit App -> Scopes -> Add or remove scopes.
enable Gmail scope

API scopes

Gmail supports IMAP/POP + OAuth, but the API (https://mail.google.com/) scope is restricted API which requests to have full access to the Gmail account. Restricted API is throttled before your project is authenticated in by Google.

Authorized Redirect URIs

If you use OAuth in a web application, you should use a web page or controller to get authorization code from Google OAuth Server. So you need to add your page or web application routing path to Authorized Redirect URIs in APIs & Services -> Dashboard -> Credentials -> OAuth 2.0 Client IDs -> Your Client ID.

Authorized Redirect URIs

Test and publish your app

By default, your app is in test mode, you should add the user email address to the test users, then the user can test your app.

Go to OAuth consent screen -> Test users -> Add users -> input the user email address.

If you want to publish your app, you should submit your app for verification by clicking “Publish”.

Authorized Redirect URIs

If your users are seeing the “unverified app” screen, it is because your OAuth request includes additional scopes that haven’t been approved. The user can still choose to proceed with the request, but the app will be limited in the number of users that can grant permission to your app when requesting unapproved sensitive or restricted scopes.

Learn more detail from: https://developers.google.com/workspace/guides/create-project.

Enable TLS Strong Encryption Algorithms in .NET 2.0 and .NET 4.0

Because HttpWebRequest is used to get access token from web service. If you’re using legacy .NET framework (.NET 2.0 - .NET 3.5 and .NET 4.0 - 4.6.1), you need to enable Strong Encryption Algorithms to request access token:

Put the following content to a file named NetStrongEncrypt.reg, right-click this file -> Merge -> Yes. You can also download it from https://www.emailarchitect.net/webapp/download/NetStrongEncrypt.zip.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v2.0.50727]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v2.0.50727]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

Use client id and client secret to request access token

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

  • Your application uses a web browser/browser control to open Oauth Url;
  • User inputs user and password in web authentication page, and then the Oauth server returns access token back to your application;
  • Your application uses access token to access resource on the server.
  • You can find full example codes in EAGetMail Installation Path\Samples_{Programming language/Developer Tool} project.

Access token expiration and refresh token

You don’t have to open browser to request access token every time. By default, access token expiration time is 3600 seconds, you can use the access token repeatedly before it is expired. After it is expired, you can use refresh token to refresh access token directly without opening browser. You can find full sample project in EAGetMail installation path to learn how to refresh token.

Important

You should create your client id and client secret, do not use the client id from example codes in production environment, it is used for test purpose. If you got "This app isn't verified" information, please click "Advanced" -> Go to ... for test.

VB6 - Retrieve email using Google OAuth from Gmail IMAP server

Here is a console application which demonstrates how to use Google OAuth to do user authentication and retrieve email.

Note

This sample cannot handle the event of Web Browser is closed by user manually before authentication is completed. You can refer to the better sample project which uses Web Browser Control in EAGetMail installation path.

Option Explicit

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

Const GetMailInfos_All = 1
Const GetMailInfos_NewOnly = 2
Const GetMailInfos_ReadOnly = 4
Const GetMailInfos_SeqRange = 8
Const GetMailInfos_UIDRange = 16
Const GetMailInfos_PR_ENTRYID = 32
Const GetMailInfos_DateRange = 64
Const GetMailInfos_OrderByDateTime = 128

' client configuration
' You should create your client id and client secret,
' do not use the following client id in production environment, it is used for test purpose only.
Const clientID = "570831866161-ha6qpdnke22f7mhf0d50ui22f427drjt.apps.googleusercontent.com"
Const clientSecret = "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"
Const scope = "openid%20profile%20email%20https://mail.google.com"
Const authUri = "https://accounts.google.com/o/oauth2/v2/auth"
Const tokenUri = "https://www.googleapis.com/oauth2/v4/token"

Public Sub DoOauthAndRetrieveEmail()

    Dim httpListener As New EAGetMailObjLib.httpListener

    ' Creates a redirect URI using an available port on the loopback address.
    If Not httpListener.Create("127.0.0.1", 0) Then
        Debug.Print "Failed to listen on " & httpListener.GetLastError()
        Exit Sub
    End If

    Dim szUri
    szUri = "http://127.0.0.1:" & httpListener.ListenPort

    Debug.Print "listen on " & szUri

    ' Creates the OAuth 2.0 authorization request.
    Dim authorizationRequest
    authorizationRequest = authUri
    authorizationRequest = authorizationRequest & "?response_type=code&scope="
    authorizationRequest = authorizationRequest & scope
    authorizationRequest = authorizationRequest & "&redirect_uri="
    authorizationRequest = authorizationRequest & szUri
    authorizationRequest = authorizationRequest & "&client_id="
    authorizationRequest = authorizationRequest & clientID

    Debug.Print "open " & authorizationRequest
    ' Opens request in the browser.
    Dim browserUi As New EAGetMailObjLib.browserUi
    browserUi.OpenUrl authorizationRequest

    ' Waits for the OAuth authorization response.
    Do While True
        If Not httpListener.GetRequestUrl(100) Then
            Debug.Print "Failed to wait:"
            Debug.Print httpListener.GetLastError()
            Exit Do
        End If

        If httpListener.RequestUrl <> "" Then
            Exit Do
        End If

        DoEvents
    Loop

    ' Send response and stop http listener.
    httpListener.SendResponse "200", "text/html; charset=utf-8", "<html><head></head><body>Please return to the app and close current window.</body></html>"
    httpListener.Close

    Dim requestUri
    requestUri = httpListener.RequestUrl
    Debug.Print "RequestUri: " & requestUri

    Dim errorCode
    ' Checks for errors.
    errorCode = ParseParameter(requestUri, "error=")
    If errorCode <> "" Then
        Debug.Print "OAuth authorization error: " & errorCode
        Exit Sub
    End If

    ' Check authorization code
    Dim code
    code = ParseParameter(requestUri, "code=")
    If code = "" Then
        Debug.Print "Malformed authorization response: " & requestUri
        Exit Sub
    End If

    Debug.Print "Authorization code: " & code

    Dim responseText
    responseText = RequestAccessToken(code, szUri)
    Debug.Print responseText

    Dim parser As New EAGetMailObjLib.OAuthResponseParser
    parser.Load responseText

    Dim user, accessToken

    user = parser.EmailInIdToken
    accessToken = parser.accessToken

    If accessToken = "" Then
        Debug.Print "Failed to request access token, return!"
        Exit Sub
    End If

    Debug.Print "User: " & user
    Debug.Print "AccessToken: " & accessToken

    RetrieveEmailWithXOAUTH2 user, accessToken
End Sub

' path?parameter1=value1&parameter2=value2#anchor;
Private Function ParseParameter(ByVal uri As String, ByVal key As String) As String

    ParseParameter = ""

    If uri = "" Or key = "" Then
        Exit Function
    End If

    Dim pos As Integer
    pos = InStr(1, uri, "?")
    If pos <= 0 Then
        Exit Function
    End If

    uri = Mid(uri, pos + 1)
    Dim i, parameters, uriParameter
    parameters = Split(uri, "&")

    For i = LBound(parameters) To UBound(parameters)
        uriParameter = parameters(i)
        If InStr(1, uriParameter, key, vbTextCompare) = 1 Then
            Dim value
            value = Mid(uriParameter, Len(key) + 1)

            pos = InStr(1, value, "#")
            If pos > 0 Then
                value = Mid(value, 1, pos - 1)
            End If

            ParseParameter = value
            Exit Function
        End If
    Next


End Function

Private Function RequestAccessToken(ByVal code As String, ByVal redirectUri As String) As String

    Debug.Print "Exchanging code for tokens..."
    RequestAccessToken = ""

    Dim responseText
    responseText = ""

    Dim httpRequest
    Set httpRequest = CreateObject("MSXML2.ServerXMLHTTP.6.0")

    Dim tokenRequestBody
    tokenRequestBody = "code="
    tokenRequestBody = tokenRequestBody & code
    tokenRequestBody = tokenRequestBody & "&redirect_uri="
    tokenRequestBody = tokenRequestBody & redirectUri
    tokenRequestBody = tokenRequestBody & "&client_id="
    tokenRequestBody = tokenRequestBody & clientID
    tokenRequestBody = tokenRequestBody & "&client_secret="
    tokenRequestBody = tokenRequestBody & clientSecret
    tokenRequestBody = tokenRequestBody & "&grant_type=authorization_code"

    httpRequest.setOption 2, 13056
    httpRequest.Open "POST", tokenUri, True
    httpRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    httpRequest.Send tokenRequestBody

    Do While httpRequest.ReadyState <> 4
        DoEvents
        httpRequest.waitForResponse (1)
    Loop

    Dim Status
    Status = httpRequest.Status
    responseText = httpRequest.responseText

    RequestAccessToken = responseText

    If Status < 200 Or Status >= 300 Then
        Debug.Print "Failed to refresh access token from server."
    End If

End Function

Private Sub RetrieveEmailWithXOAUTH2(ByVal userEmail As String, ByVal accessToken As String)
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    ' Gmail IMAP4 Server address
    oServer.Server = "imap.gmail.com"
    ' Use OAUTH 2.0
    oServer.AuthType = MailServerAuthXOAUTH2
    oServer.user = userEmail
    ' Use access token as password
    oServer.Password = accessToken
    oServer.Protocol = MailServerImap4

    ' Enable SSL/TLS connection
    oServer.SSLConnection = True
    ' Set IMAP SSL Port
    oServer.Port = 993


On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    Debug.Print "Connecting " & oServer.Server & "..."
    oClient.Connect oServer
    Debug.Print "Connected"

    ' Get new email only, if you want to get all emails, please remove this line
    oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfos_NewOnly

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    Debug.Print infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        Debug.Print "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from IMAP4 server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        Debug.Print "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' 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 = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Mark email as read to prevent retrieving this email again.
        oClient.MarkAsRead info, True

        ' If you want to delete current email, please use Delete method instead of MarkAsRead
        ' oClient.Delete info
    Next

    ' Quit and expunge emails marked as deleted from IMAP4 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    Debug.Print Err.Description
End Sub

VBScript/ASP - Retrieve email using Google OAuth from Gmail IMAP server in ASP

If you use Google OAuth in ASP.NET/ASP MVC application, you should use a ASP.NET page or ASP MVC Controller to get authorization code instead of HttpListener. You need to add your ASP.NET page or ASP MVC Controller routing path to Authorized Redirect URIs in your Google project.

' Please add http://localhost:54098/oauth/token.asp to Authorized redirect URIs in your Google/MS Azure project.
Dim code
code = Request.QueryString("code")

TLS 1.2 protocol

TLS is the successor of SSL, more and more SMTP servers require TLS 1.2 encryption now.

If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2, you need to enable TLS 1.2 protocol in your operating system like this:

Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012

Appendix

Comments

If you have any comments or questions about above example codes, please click here to add your comments.