VB6/ASP - Send Email using Google/Gmail OAuth 2.0 Authentication

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

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

Installation

EASendMail is a SMTP component which supports all operations of SMTP/ESMTP protocols (RFC 821, RFC 822, RFC 2554). Before you can use the following example codes, you should download the EASendMail Installer and install it on your machine at first.

Add Reference in VB6

To use EASendMail SMTP ActiveX Object in your project, the first step is “Add reference of EASendMail to your project”. Please select menu -> Project -> References -> and select EASendMailObj ActiveX Object, click OK, the reference will be added to current project, and you can start to use it to send email in your VB6 project.

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 send email in your VBA project.

add reference in VB 6.0

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 send email using Gmail OAuth in your application, you should create a project in Google Developers Console like this:

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

    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

  • Set detail information for your project at "OAuth consent screen" -> "Edit App".

    edit Gmail oauth consent
  • Finally add "https://mail.google.com/" and "../auth/gmail.send" scopes at "OAuth consent screen" -> "Edit App" -> "Scopes for Google API".

    enable Gmail scope

API Scopes

Gmail supports SMTP + 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.

Using less restricted API (https://www.googleapis.com/auth/gmail.send) scope to send email via Gmail server is recommended.

  • If you use Gmail RESTFul API to send email, please only use "../auth/gmail.send" scope to avoid your app throttled;
  • If you use SMTP protocol, you should use https://mail.google.com/ scope.

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

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 Google OAUTH URL;
  • User inputs user and password in Google Web Authentication Page, and then Google returns access token back to your application;
  • Your application uses access token to access Gmail SMTP server.
  • You can find full example codes in EASendMail Installation Path\Samples_{Programming language/Developer Tool}\Oauth project.

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 - Send Email Using Google OAuth + Gmail SMTP Server

Here is a simple application which demonstrates how to use Google OAuth to do user authentication and send 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 EASendMail installation path.

Option Explicit

Const ConnectNormal = 0
Const ConnectSSLAuto = 1
Const ConnectSTARTTLS = 2
Const ConnectDirectSSL = 3
Const ConnectTryTLS = 4

Const AuthAuto = -1
Const AuthLogin = 0
Const AuthNtlm = 1
Const AuthCramMd5 = 2
Const AuthPlain = 3
Const AuthMsn = 4
Const AuthXoauth2 = 5

' 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 = "1072602369179-aru4rj97ateiho9rt4pf5i8l1r01mc16.apps.googleusercontent.com"
Const clientSecret = "Lnw8r5FvfKFNS_CSEucbdIE-"
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 DoOauthAndSendEmail()

    Dim httpListener As New EASendMailObjLib.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 EASendMailObjLib.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 EASendMailObjLib.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

    SendMailWithXOAUTH2 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 SendMailWithXOAUTH2(ByVal userEmail As String, ByVal accessToken As String)
    Dim oSmtp As New EASendMailObjLib.Mail
    oSmtp.LicenseCode = "TryIt"

    ' Gmail SMTP server address
    oSmtp.ServerAddr = "smtp.gmail.com"
    ' Using 587 port, you can also use 465 or 25 port
    oSmtp.ServerPort = 587

    ' Enable SSL/TLS connection
    oSmtp.ConnectType = ConnectSSLAuto

    ' OAUTH/XOAUTH2 type
    oSmtp.AuthType = AuthXoauth2
    ' set user authentication
    oSmtp.UserName = userEmail
    ' use access token as password
    oSmtp.Password = accessToken

    ' Your email address
    oSmtp.FromAddr = userEmail
    ' Please change recipient address to yours for test
    oSmtp.AddRecipient "Support Team", "support@emailarchitect.net", 0

    oSmtp.Subject = "Test email using Gmail Oauth"
    oSmtp.BodyText = "Hello, this is a test...."

    Debug.Print "start to send email using OAUTH 2.0 ..."
    If oSmtp.SendMail() = 0 Then
        Debug.Print "The email has been submitted to server successfully!"
    Else
        Debug.Print oSmtp.GetLastErrDescription()
    End If

End Sub

VBScript/ASP - Send Email Using Google OAuth + Gmail SMTP Server

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

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

You can find a full sample project in EASendMail installation path\Samples_ASPClassic.

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.