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

Lua
local chilkat = require("chilkat")

local success = false

-- Assumes Chilkat is unlocked. See Global Unlock Sample.

local files = chilkat.FileAccess.new()
-- Recover the previous complete file if a run stopped during replacement.
local fileStatus = files:file_exists3("gmail-token.json")
if fileStatus < 0 then
    print("Could not inspect gmail-token.json.")
    return
end

if fileStatus == 0 then
    local backupStatus = files:file_exists3("gmail-token.json.previous")
    if backupStatus < 0 then
        print("Could not inspect the backup file.")
        return
    end

    if backupStatus == 1 then
        success = files:file_rename("gmail-token.json.previous", "gmail-token.json")
        if not success then
            print("Could not restore the previous complete file.")
            return
        end

        fileStatus = 1
    end
end

local token = chilkat.JsonObject.new()
success = token:load_file("gmail-token.json")
if not success then
    print("Could not read gmail-token.json from the private working directory.")
    return
end

if (token:json_type_of("refresh_token") ~= 1) or (token:string_of_equals("refresh_token", "", true)) then
    print("Authorize this account for offline access first.")
    return
end

local client = chilkat.JsonObject.new()
success = client:load_file("gmail-client.json")
if not success then
    print("Could not load the private OAuth client file.")
    return
end

if (client:json_type_of("client_id") ~= 1) or (client:json_type_of("client_secret") ~= 1) then
    print("gmail-client.json must contain client_id and client_secret.")
    return
end

local http = chilkat.Http.new()
http.require_ssl_cert_verify = true
local form = chilkat.HttpRequest.new()
form.http_verb = "POST"
form.content_type = "application/x-www-form-urlencoded"
form:add_param("grant_type", "refresh_token")
form:add_param("client_id", client:string_of("client_id"))
form:add_param("client_secret", client:string_of("client_secret"))
form:add_param("refresh_token", token:string_of("refresh_token"))
local resp = chilkat.HttpResponse.new()
local reply = chilkat.JsonObject.new()
success = http:http_req("https://oauth2.googleapis.com/token", form, resp)
if resp.status_code == 0 then
    print("The token endpoint did not return an HTTP response.")
    return
end

if (not success) or (resp.status_code ~= 200) then
    print("Token refresh failed. HTTP " .. resp.status_code)
    success = reply:load(resp.body_str)
    if success then
        if reply:string_of_equals("error", "invalid_grant", true) then
            print("Reconnect this account with interactive authorization.")
        end
    end

    return
end

success = reply:load(resp.body_str)
if not success then
    print("Could not parse the refresh response.")
    return
end

if (reply:json_type_of("access_token") ~= 1) or (reply:string_of_equals("access_token", "", true)) then
    print("Expected access_token in the response.")
    return
end

-- Google usually omits the refresh token. Preserve it unless a replacement is returned.
if (reply:json_type_of("refresh_token") ~= 1) or (reply:string_of_equals("refresh_token", "", true)) then
    success = reply:update_string("refresh_token", token:string_of("refresh_token"))
    if not success then
        print(reply.last_error_text)
        return
    end
end

if (not reply:has_member("scope")) and (token:json_type_of("scope") == 1) then
    success = reply:update_string("scope", token:string_of("scope"))
    if not success then
        print(reply.last_error_text)
        return
    end
end

-- Prepare the complete replacement before moving the last committed file.
success = reply:write_file("gmail-token.json.new")
if not success then
    print("Could not write the replacement file.")
    return
end

if files:file_exists("gmail-token.json") then
    if files:file_exists("gmail-token.json.previous") then
        success = files:file_delete("gmail-token.json.previous")
        if not success then
            print("Could not rotate the previous backup.")
            return
        end
    end

    success = files:file_rename("gmail-token.json", "gmail-token.json.previous")
    if not success then
        print("Could not retain the previous complete file.")
        return
    end
end

success = files:file_rename("gmail-token.json.new", "gmail-token.json")
if not success then
    print("Could not commit the replacement. The previous complete file is retained.")
    return
end

http.auth_token = reply:string_of("access_token")
success = http:http_no_body("GET", "https://gmail.googleapis.com/gmail/v1/users/me/messages?labelIds=INBOX&maxResults=10", resp)
if resp.status_code == 0 then
    print("Gmail did not return an HTTP response.")
    return
end

if (not success) or ((resp.status_code < 200) or (resp.status_code >= 300)) then
    print("Gmail HTTP " .. resp.status_code)
    success = reply:load(resp.body_str)
    if success then
        print(reply:string_of("error.message"))
    end

    return
end

success = reply:load(resp.body_str)
if not success then
    print("Expected a Gmail JSON response.")
    return
end

local ids = chilkat.StringTable.new()
local i = 0
while i < reply:size_of_array("messages") do
    reply.i = i
    success = ids:append(reply:string_of("messages[i].id"))
    if not success then
        print(ids.last_error_text)
        return
    end

    i = i + 1
end

local url = chilkat.StringBuilder.new()
i = 0
while i < ids.count do
    url:set_string("https://gmail.googleapis.com/gmail/v1/users/me/messages/")
    url:append(http:url_encode(ids:string_at(i)))
    url:append("?format=metadata&metadataHeaders=From&metadataHeaders=Subject")
    success = http:http_no_body("GET", url:get_as_string(), resp)
    if resp.status_code == 0 then
        print("Gmail did not return an HTTP response.")
        return
    end

    if (not success) or ((resp.status_code < 200) or (resp.status_code >= 300)) then
        print("Gmail HTTP " .. resp.status_code)
        success = reply:load(resp.body_str)
        if success then
            print(reply:string_of("error.message"))
        end

        return
    end

    success = reply:load(resp.body_str)
    if not success then
        print("Expected a Gmail JSON response.")
        return
    end

    print("Message: " .. ids:string_at(i))
    local h = 0
    while h < reply:size_of_array("payload.headers") do
        reply.i = h
        print(reply:string_of("payload.headers[i].name") .. ": " .. reply:string_of("payload.headers[i].value"))
        h = h + 1
    end

    i = i + 1
end

print("Inbox messages checked: " .. ids.count)