Sample code for 30+ languages & platforms
PureBasic 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 PureBasic Downloads

PureBasic
IncludeFile "CkSocket.pb"
IncludeFile "CkAuthGoogle.pb"
IncludeFile "CkHttpResponse.pb"
IncludeFile "CkJsonObject.pb"
IncludeFile "CkHttp.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  Assumes Chilkat is unlocked. See Global Unlock Sample.

    key.i = CkJsonObject::ckCreate()
    If key.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckLoadFile(key,"gmail-service-account.json")
    If success <> 1
        Debug "Could not load the service-account key from the private directory."
        CkJsonObject::ckDispose(key)
        ProcedureReturn
    EndIf

    auth.i = CkAuthGoogle::ckCreate()
    If auth.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkAuthGoogle::setCkJsonKey(auth, CkJsonObject::ckEmit(key))
    CkAuthGoogle::setCkScope(auth, "https://www.googleapis.com/auth/gmail.metadata")
    CkAuthGoogle::setCkSubEmailAddress(auth, "user@example.com")
    CkAuthGoogle::setCkExpireNumSeconds(auth, 3600)

    ;  Obtain a token for the named Workspace user. Keep the computer clock accurate.
    connection.i = CkSocket::ckCreate()
    If connection.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkSocket::setCkRequireSslCertVerify(connection, 1)
    success = CkSocket::ckConnect(connection,"www.googleapis.com",443,1,10000)
    If success <> 1
        Debug "Could not establish the Google token connection."
        CkJsonObject::ckDispose(key)
        CkAuthGoogle::ckDispose(auth)
        CkSocket::ckDispose(connection)
        ProcedureReturn
    EndIf

    success = CkAuthGoogle::ckObtainAccessToken(auth,connection)
    CkSocket::ckClose(connection,1000)
    If success <> 1
        Debug "Token exchange failed. Check the key, delegated scopes, user, and computer clock."
        CkJsonObject::ckDispose(key)
        CkAuthGoogle::ckDispose(auth)
        CkSocket::ckDispose(connection)
        ProcedureReturn
    EndIf

    http.i = CkHttp::ckCreate()
    If http.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkHttp::setCkRequireSslCertVerify(http, 1)
    CkHttp::setCkAuthToken(http, CkAuthGoogle::ckAccessToken(auth))
    resp.i = CkHttpResponse::ckCreate()
    If resp.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    reply.i = CkJsonObject::ckCreate()
    If reply.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkHttp::ckHttpNoBody(http,"GET","https://gmail.googleapis.com/gmail/v1/users/me/profile",resp)
    If CkHttpResponse::ckStatusCode(resp) = 0
        Debug "Gmail did not return an HTTP response."
        CkJsonObject::ckDispose(key)
        CkAuthGoogle::ckDispose(auth)
        CkSocket::ckDispose(connection)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(reply)
        ProcedureReturn
    EndIf

    If (success <> 1) OR (CkHttpResponse::ckStatusCode(resp) < 200) OR (CkHttpResponse::ckStatusCode(resp) >= 300)
        Debug "Gmail HTTP " + Str(CkHttpResponse::ckStatusCode(resp))
        success = CkJsonObject::ckLoad(reply,CkHttpResponse::ckBodyStr(resp))
        If success = 1
            Debug CkJsonObject::ckStringOf(reply,"error.message")
        EndIf

        CkJsonObject::ckDispose(key)
        CkAuthGoogle::ckDispose(auth)
        CkSocket::ckDispose(connection)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(reply)
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckLoad(reply,CkHttpResponse::ckBodyStr(resp))
    If success <> 1
        Debug "Expected a Gmail JSON response."
        CkJsonObject::ckDispose(key)
        CkAuthGoogle::ckDispose(auth)
        CkSocket::ckDispose(connection)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(reply)
        ProcedureReturn
    EndIf

    If (CkJsonObject::ckJsonTypeOf(reply,"emailAddress") <> 1) OR (CkJsonObject::ckStringOfEquals(reply,"emailAddress","",1) = 1)
        Debug "Expected emailAddress in the response."
        CkJsonObject::ckDispose(key)
        CkAuthGoogle::ckDispose(auth)
        CkSocket::ckDispose(connection)
        CkHttp::ckDispose(http)
        CkHttpResponse::ckDispose(resp)
        CkJsonObject::ckDispose(reply)
        ProcedureReturn
    EndIf

    Debug "Authorized mailbox: " + CkJsonObject::ckStringOf(reply,"emailAddress")
    Debug "Messages: " + Str(CkJsonObject::ckIntOf(reply,"messagesTotal"))


    CkJsonObject::ckDispose(key)
    CkAuthGoogle::ckDispose(auth)
    CkSocket::ckDispose(connection)
    CkHttp::ckDispose(http)
    CkHttpResponse::ckDispose(resp)
    CkJsonObject::ckDispose(reply)


    ProcedureReturn
EndProcedure