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

Check Gmail from a scheduled job after one-time consent

See more GMail REST API Examples

First run desktop authorization with gmail.readonly and offline access. This applies to personal Gmail and Workspace accounts subject to organization policies. Configure a job to run this code using the same private working directory and user identity. Each run refreshes the token and displays up to ten inbox message headers.

Save the original OAuth client credentials in a private gmail-client.json containing client_id and client_secret. The existing gmail-token.json supplies the refresh token. Use protected credential storage in a deployed application and serialize runs sharing these files. An invalid_grant response requires reconnecting the account. External OAuth apps in Testing normally receive refresh tokens that expire after seven days when Gmail scopes are requested. Google token expiration guidance.

This is a repeatable inbox check. To process each mailbox change across runs, see mailbox synchronization.

Google documentation

Chilkat Ruby Downloads

Ruby
require 'chilkat'

success = false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

files = Chilkat::CkFileAccess.new()
#  Recover the previous complete file if a run stopped during replacement.
fileStatus = files.FileExists3("gmail-token.json")
if (fileStatus < 0)
    print "Could not inspect gmail-token.json." + "\n";
    exit
end

if (fileStatus == 0)
    backupStatus = files.FileExists3("gmail-token.json.previous")
    if (backupStatus < 0)
        print "Could not inspect the backup file." + "\n";
        exit
    end

    if (backupStatus == 1)
        success = files.FileRename("gmail-token.json.previous","gmail-token.json")
        if (success != true)
            print "Could not restore the previous complete file." + "\n";
            exit
        end

        fileStatus = 1
    end

end

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

if ((token.JsonTypeOf("refresh_token") != 1) or (token.StringOfEquals("refresh_token","",true) == true))
    print "Authorize this account for offline access first." + "\n";
    exit
end

client = Chilkat::CkJsonObject.new()
success = client.LoadFile("gmail-client.json")
if (success != true)
    print "Could not load the private OAuth client file." + "\n";
    exit
end

if ((client.JsonTypeOf("client_id") != 1) or (client.JsonTypeOf("client_secret") != 1))
    print "gmail-client.json must contain client_id and client_secret." + "\n";
    exit
end

http = Chilkat::CkHttp.new()
http.put_RequireSslCertVerify(true)
form = Chilkat::CkHttpRequest.new()
form.put_HttpVerb("POST")
form.put_ContentType("application/x-www-form-urlencoded")
form.AddParam("grant_type","refresh_token")
form.AddParam("client_id",client.stringOf("client_id"))
form.AddParam("client_secret",client.stringOf("client_secret"))
form.AddParam("refresh_token",token.stringOf("refresh_token"))
resp = Chilkat::CkHttpResponse.new()
reply = Chilkat::CkJsonObject.new()
success = http.HttpReq("https://oauth2.googleapis.com/token",form,resp)
if (resp.get_StatusCode() == 0)
    print "The token endpoint did not return an HTTP response." + "\n";
    exit
end

if ((success != true) or (resp.get_StatusCode() != 200))
    print "Token refresh failed. HTTP " + resp.get_StatusCode().to_s() + "\n";
    success = reply.Load(resp.bodyStr())
    if (success == true)
        if (reply.StringOfEquals("error","invalid_grant",true) == true)
            print "Reconnect this account with interactive authorization." + "\n";
        end

    end

    exit
end

success = reply.Load(resp.bodyStr())
if (success != true)
    print "Could not parse the refresh response." + "\n";
    exit
end

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

#  Google usually omits the refresh token. Preserve it unless a replacement is returned.
if ((reply.JsonTypeOf("refresh_token") != 1) or (reply.StringOfEquals("refresh_token","",true) == true))
    success = reply.UpdateString("refresh_token",token.stringOf("refresh_token"))
    if (success != true)
        print reply.lastErrorText() + "\n";
        exit
    end

end

if ((reply.HasMember("scope") != true) and (token.JsonTypeOf("scope") == 1))
    success = reply.UpdateString("scope",token.stringOf("scope"))
    if (success != true)
        print reply.lastErrorText() + "\n";
        exit
    end

end

#  Prepare the complete replacement before moving the last committed file.
success = reply.WriteFile("gmail-token.json.new")
if (success != true)
    print "Could not write the replacement file." + "\n";
    exit
end

if (files.FileExists("gmail-token.json") == true)
    if (files.FileExists("gmail-token.json.previous") == true)
        success = files.FileDelete("gmail-token.json.previous")
        if (success != true)
            print "Could not rotate the previous backup." + "\n";
            exit
        end

    end

    success = files.FileRename("gmail-token.json","gmail-token.json.previous")
    if (success != true)
        print "Could not retain the previous complete file." + "\n";
        exit
    end

end

success = files.FileRename("gmail-token.json.new","gmail-token.json")
if (success != true)
    print "Could not commit the replacement. The previous complete file is retained." + "\n";
    exit
end

http.put_AuthToken(reply.stringOf("access_token"))
success = http.HttpNoBody("GET","https://gmail.googleapis.com/gmail/v1/users/me/messages?labelIds=INBOX&maxResults=10",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

ids = Chilkat::CkStringTable.new()
i = 0
while (i < reply.SizeOfArray("messages"))
    reply.put_I(i)
    success = ids.Append(reply.stringOf("messages[i].id"))
    if (success != true)
        print ids.lastErrorText() + "\n";
        exit
    end

    i = i + 1
end
url = Chilkat::CkStringBuilder.new()
i = 0
while (i < ids.get_Count())
    url.SetString("https://gmail.googleapis.com/gmail/v1/users/me/messages/")
    url.Append(http.urlEncode(ids.stringAt(i)))
    url.Append("?format=metadata&metadataHeaders=From&metadataHeaders=Subject")
    success = http.HttpNoBody("GET",url.getAsString(),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

    print "Message: " + ids.stringAt(i) + "\n";
    h = 0
    while (h < reply.SizeOfArray("payload.headers"))
        reply.put_I(h)
        print reply.stringOf("payload.headers[i].name") + ": " + reply.stringOf("payload.headers[i].value") + "\n";
        h = h + 1
    end
    i = i + 1
end
print "Inbox messages checked: " + ids.get_Count().to_s() + "\n";