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

Ruby
require 'chilkat'

success = false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

key = Chilkat::CkJsonObject.new()
success = key.LoadFile("gmail-service-account.json")
if (success != true)
    print "Could not load the service-account key from the private directory." + "\n";
    exit
end

auth = Chilkat::CkAuthGoogle.new()
auth.put_JsonKey(key.emit())
auth.put_Scope("https://www.googleapis.com/auth/gmail.metadata")
auth.put_SubEmailAddress("user@example.com")
auth.put_ExpireNumSeconds(3600)

#  Obtain a token for the named Workspace user. Keep the computer clock accurate.
connection = Chilkat::CkSocket.new()
connection.put_RequireSslCertVerify(true)
success = connection.Connect("www.googleapis.com",443,true,10000)
if (success != true)
    print "Could not establish the Google token connection." + "\n";
    exit
end

success = auth.ObtainAccessToken(connection)
connection.Close(1000)
if (success != true)
    print "Token exchange failed. Check the key, delegated scopes, user, and computer clock." + "\n";
    exit
end

http = Chilkat::CkHttp.new()
http.put_RequireSslCertVerify(true)
http.put_AuthToken(auth.accessToken())
resp = Chilkat::CkHttpResponse.new()
reply = Chilkat::CkJsonObject.new()
success = http.HttpNoBody("GET","https://gmail.googleapis.com/gmail/v1/users/me/profile",resp)
if (resp.get_StatusCode() == 0)
    print "Gmail did not return an HTTP response." + "\n";
    exit
end

if ((success != true) or (resp.get_StatusCode() < 200) or (resp.get_StatusCode() >= 300))
    print "Gmail HTTP " + resp.get_StatusCode().to_s() + "\n";
    success = reply.Load(resp.bodyStr())
    if (success == true)
        print reply.stringOf("error.message") + "\n";
    end

    exit
end

success = reply.Load(resp.bodyStr())
if (success != true)
    print "Expected a Gmail JSON response." + "\n";
    exit
end

if ((reply.JsonTypeOf("emailAddress") != 1) or (reply.StringOfEquals("emailAddress","",true) == true))
    print "Expected emailAddress in the response." + "\n";
    exit
end

print "Authorized mailbox: " + reply.stringOf("emailAddress") + "\n";
print "Messages: " + reply.IntOf("messagesTotal").to_s() + "\n";