VB6/ASP - Send email using Gmail/G Suite OAuth 2.0 in background service (service account)

By default, you need to enable ” Allowing less secure apps” in Gmail/G Suite/Google Workspace, 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

Google Service Account

Normal OAuth requires user input user/password in Web Browser. Obviously, it is not suitable for background service. In this case, you should use google service account to access G Suite or Google Workspace email service without user interaction. Service account only works for G Suite or Google Workspace user, it doesn’t work for personal Gmail account.

Create project in Google Developers Console

To use “G Suite or Google Workspace Service Account OAuth” in your application, you should create a project in Google Cloud Console at first.

Important

You can use any google user to create service account, it doesn’t require service account owner is a user in G Suite. But G Suite or Google Workspace administrator must authorize service account in Google Admin Console to access user mailbox.

Create service account in current project

  • Click "Credentials" -> "Manage service accounts"

    manage service account in google developers console
  • Click "CREATE SERVICE ACCOUNT"

    create service account in google developers console
  • Input a name for your service account, click "DONE"

After service account is created, you should enable "Domain-wide delegation" and create service key pair to access G Suite or Google Workspace user mailbox.

Create service key

  • Go back to your service account -> Keys, click Add Key, you can select "p12" or "json" key type, both can work well, then you will get a file which contains private key, save the file to local disk.

    Now you have created service account with key pair successfully. You can use created private key in your codes to request "access token" impersonating a user in G Suite or Google Workspace.

create service key
  • To access user data in G Suite, you must get authorization from G Suite or Google Workspace administrator. You should go back to your service account -> Details, copy your service account email address and client id.
google oauth client id

Enable Gmail API

Enable Gmail API in "Library" -> Search "Gmail", then click "Gmail API" and enable it. If you use Gmail API protocol to send email, you should enable this API, if you use SMTP protocol, you don’t have to enable it.

enable Gmail API

Authorize service account by G Suite administrator

To use service account to access user mailbox in G Suite or Google Workspace, G Suite Administrator should authorize specified service account at first.

Important

Important Notice: You can use any google user to create service account, it doesn’t require service account owner is a user in G Suite or Google Workspace. But G Suite or Google Workspace administrator must authorize service account in G Suite or Google Workspace Admin Console to access user mailbox.

  • The administrator should open admin.google.com, go to Admin Console, click "Security" > API Control;

    Authorize Service Account by G Suite Administrator
  • In the Domain wide delegation pane, select Manage Domain Wide Delegation.

  • Click Add new.

  • In the Client ID field, enter the service account’s Client ID

  • Click Add new and enter your service account client ID.

  • Enter the client ID of the service account or OAuth2 client ID of the app.

  • In the OAuth scopes (comma-delimited) field, enter the list of scopes that your application should be granted access to. and input https://mail.google.com/, email, profile in One or More API Scopes, click "Authorize".

manage api client access by G Suite Administrator 1
  • Click Authorize.

After the administrator authorized service account, you can use it to access any users mailbox in G Suite or Google Workspace domain.

Learn more detail from: https://developers.google.com/identity/protocols/oauth2/service-account

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 .NET framework (.NET 2.0 - 3.5 and .NET 4.x), 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

Access token lifetime

You don’t have to request access token every time. By default, access token expiration time is 3600 seconds, you can reuse the access token repeatedly before it is expired.

VB6/ASP - Send email using Gmail/G Suite OAuth 2.0 with service account - example

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

Const CRYPT_MACHINE_KEYSET = 32
Const CRYPT_USER_KEYSET = 4096

Private Function GenerateRequestData(GsuiteUser)

    GenerateRequestData = ""

    ' service account email address
    Const serviceAccount = "xxxxxx@xxxxxx.iam.gserviceaccount.com"
    Const scope = "https://mail.google.com/"
    Const aud = "https://oauth2.googleapis.com/token"

    Dim jwt As New EASendMailObjLib.SimpleJsonParser

    Dim header, playload
    header = jwt.JwtBase64UrlEncode("{""alg"":""RS256"",""typ"":""JWT""}")

    Dim iat, exp
    ' token request timestamp
    iat = jwt.GetCurrentIAT()
    ' token expiration time
    exp = iat + 3600

    playload = "{"
    playload = playload & """iss"":""" & serviceAccount & ""","
    playload = playload & """scope"":""" & scope & ""","
    playload = playload & """aud"":""" & aud & ""","
    playload = playload & """exp"":" & exp & ","
    playload = playload & """iat"":" & iat & ","
    playload = playload & """sub"":""" & GsuiteUser & """"
    playload = playload & "}"

    playload = jwt.JwtBase64UrlEncode(playload)

    Dim cert As New EASendMailObjLib.Certificate

    ' In web application, use CRYPT_MACHINE_KEYSET
    If Not cert.LoadPFXFromFile("D:\myfolder\myoauth-77dec4d192ec.p12", "notasecret", CRYPT_USER_KEYSET) Then
        MsgBox "Failed to load service account certificate!"
        Exit Function
    End If

    Dim signature
    signature = jwt.SignRs256(cert, header & "." & playload)
    If signature = "" Then
        MsgBox "Failed to sign request data!"
        Exit Function
    End If

    Dim dataToPost

    dataToPost = header & "." & playload & "." & signature
    GenerateRequestData = dataToPost

End Function

Private Function RequestAccessToken(requestData)
    RequestAccessToken = ""

    If requestData = "" Then
        Exit Function
    End If

On Error GoTo ErrorHandle

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

    requestData = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" & requestData

    httpRequest.setOption 2, 13056
    httpRequest.Open "POST", "https://oauth2.googleapis.com/token", True
    httpRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    httpRequest.Send requestData

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

    Dim Status
    Status = httpRequest.Status

    If Status < 200 Or Status >= 300 Then
        MsgBox "Failed to get access token from server."
        MsgBox httpRequest.responseText
        Exit Function
    End If

    Dim result
    result = httpRequest.responseText

    Dim oauthParser As New EASendMailObjLib.OAuthResponseParser
    oauthParser.Load result

    Dim accessToken
    accessToken = oauthParser.accessToken

    If accessToken = "" Then
        MsgBox "Failed to parse access token from server response."
        Exit Function
    End If

    RequestAccessToken = accessToken
    Exit Function

ErrorHandle:
    MsgBox "Failed to request access token." & Err.Description

End Function

Private Sub SendEmail()
    ' GsuiteUser is the full email address of the user in GSuite, user@gsuitedomain
    Dim GsuiteUser As String
    GsuiteUser = "user@mydomainingsuit.com"

    Dim access_token As String
    ' request access token from Google server by service account
    ' withou user interaction
    access_token = RequestAccessToken(GenerateRequestData(GsuiteUser))

    If access_token = "" Then
        Exit Sub
    End If

    Dim oSmtp As EASendMailObjLib.Mail
    Set oSmtp = New EASendMailObjLib.Mail
    oSmtp.LicenseCode = "TryIt"

    oSmtp.ServerAddr = "smtp.gmail.com"
    oSmtp.ServerPort = 587

    ' Enable SSL/TLS connection
    oSmtp.ConnectType = ConnectSSLAuto

    ' Gmail OAUTH/XOAUTH2 type
    oSmtp.AuthType = AuthXoauth2
    oSmtp.UserName = GsuiteUser
    oSmtp.Password = access_token

    oSmtp.FromAddr = GsuiteUser
    oSmtp.AddRecipient "Support Team", "support@emailarchitect.net", 0

    oSmtp.BodyText = "Hello, this is a test...."
    If oSmtp.SendMail() = 0 Then
        MsgBox "Message delivered!"
    Else
        MsgBox oSmtp.GetLastErrDescription()
    End If

End Sub

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.