Sample code for 30+ languages & platforms
B4X Requires Chilkat v11.0.0+

Access a Google Workspace mailbox with a service account

See more GMail REST API Examples

A Google Workspace super administrator must authorize the service account client ID for https://www.googleapis.com/auth/gmail.metadata in Admin console domain-wide delegation. Enable the Gmail API in the Cloud project. Set SubEmailAddress to a Gmail-enabled user in that organization. The profile response identifies the mailbox represented by me.

Store the downloaded JSON service-account key in gmail-service-account.json in a private working directory. AuthGoogle signs a JWT with the key and exchanges it for an access token. Repeat that exchange when the token expires. For other operations, change Scope and grant that scope in the Admin console. This workflow is for organization-controlled applications. Personal Gmail accounts can use offline authorization with a refresh token.

Google documentation

Chilkat B4X Downloads

B4X
Dim success As Boolean = False

'  Assumes Chilkat is unlocked. See Global Unlock Sample.

Dim key As ChilkatJsonObject
key.Initialize
success = key.LoadFile("gmail-service-account.json")
If success <> True Then
    Log("Could not load the service-account key from the private directory.")
    Return
End If

Dim auth As ChilkatAuthGoogle
auth.Initialize("auth")
auth.JsonKey = key.Emit
auth.Scope = "https://www.googleapis.com/auth/gmail.metadata"
auth.SubEmailAddress = "user@example.com"
auth.ExpireNumSeconds = 3600

'  Obtain a token for the named Workspace user. Keep the computer clock accurate.
Dim connection As ChilkatSocket
connection.Initialize("connection")
connection.RequireSslCertVerify = True
success = connection.Connect("www.googleapis.com", 443, True, 10000)
If success <> True Then
    Log("Could not establish the Google token connection.")
    Return
End If

success = auth.ObtainAccessToken(connection)
connection.Close(1000)
If success <> True Then
    Log("Token exchange failed. Check the key, delegated scopes, user, and computer clock.")
    Return
End If

Dim http As ChilkatHttp
http.Initialize("http")
http.RequireSslCertVerify = True
http.AuthToken = auth.AccessToken
Dim resp As ChilkatHttpResponse
resp.Initialize
Dim reply As ChilkatJsonObject
reply.Initialize
success = http.HttpNoBody("GET", "https://gmail.googleapis.com/gmail/v1/users/me/profile", resp)
If resp.StatusCode = 0 Then
    Log("Gmail did not return an HTTP response.")
    Return
End If

If (success <> True) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300) Then
    Log("Gmail HTTP " & resp.StatusCode)
    success = reply.Load(resp.BodyStr)
    If success = True Then
        Log(reply.StringOf("error.message"))
    End If

    Return
End If

success = reply.Load(resp.BodyStr)
If success <> True Then
    Log("Expected a Gmail JSON response.")
    Return
End If

If (reply.JsonTypeOf("emailAddress") <> 1) Or (reply.StringOfEquals("emailAddress", "", True) = True) Then
    Log("Expected emailAddress in the response.")
    Return
End If

Log("Authorized mailbox: " & reply.StringOf("emailAddress"))
Log("Messages: " & reply.IntOf("messagesTotal"))