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

Synchronize Gmail message IDs and labels between runs

See more GMail REST API Examples

Maintain gmail-sync.json containing the mailbox address, a string historyId, and a small local cache of message IDs, thread IDs, and labels. The first run scans the complete mailbox including Spam and Trash. Later runs follow all history pages and refresh only messages affected by additions, deletions, or label changes. A message GET returning 404 removes that message from the local cache.

An expired history checkpoint causes a full rebuild. The full scan records a checkpoint before listing messages, so the next run also reconciles changes made during the scan. Incremental runs save the final history response checkpoint only after every affected message has been processed. The cache and checkpoint are committed together, with a previous-file recovery path. History IDs remain strings throughout.

Run in a private directory and serialize runs sharing the cache. The sample holds the cache in memory for clarity. Larger applications can use database upserts and deletions, committing the checkpoint in the same transaction. The cache contains message identifiers and labels. Fetch MIME or selected headers when the application needs message content.

Authorize the application with https://www.googleapis.com/auth/gmail.readonly. The example reads the access token from gmail-token.json in a private working directory. Authorize a desktop application.

Google documentation

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

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

local token = chilkat.JsonObject.new()
local 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("access_token") ~= 1) or (token:string_of_equals("access_token", "", true)) then
    print("An OAuth access token is required.")
    return
end

local http = chilkat.Http.new()
http.require_ssl_cert_verify = true
http.auth_token = token:string_of("access_token")
local resp = chilkat.HttpResponse.new()
local reply = chilkat.JsonObject.new()
local files = chilkat.FileAccess.new()
-- Recover the previous complete file if a run stopped during replacement.
local fileStatus = files:file_exists3("gmail-sync.json")
if fileStatus < 0 then
    print("Could not inspect gmail-sync.json.")
    return
end

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

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

        fileStatus = 1
    end
end

local state = chilkat.JsonObject.new()
if fileStatus == 1 then
    success = state:load_file("gmail-sync.json")
    if not success then
        print("Could not read the existing synchronization state.")
        return
    end

    if (state:json_type_of("historyId") ~= 1) or ((state:json_type_of("messages") ~= 3) or (state:json_type_of("emailAddress") ~= 1)) then
        print("The synchronization state is incomplete. Restore its previous complete copy.")
        return
    end
end

success = http:http_no_body("GET", "https://gmail.googleapis.com/gmail/v1/users/me/profile", 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

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

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

local mailbox = reply:string_of("emailAddress")
local baseline = reply:string_of("historyId")
if fileStatus == 1 then
    if not state:string_of_equals("emailAddress", mailbox, false) then
        print("Use a separate synchronization file for this mailbox.")
        return
    end
end

local fullSync = fileStatus == 0
local checkpoint = baseline
-- A hashtable collects each changed ID once, even across multiple history records.
local ids = chilkat.Hashtable.new()
local baseUrl = chilkat.StringBuilder.new()
local url = chilkat.StringBuilder.new()
local pageToken = ""
local more = true

if not fullSync then
    baseUrl:set_string("https://gmail.googleapis.com/gmail/v1/users/me/history?maxResults=500&startHistoryId=")
    baseUrl:append(http:url_encode(state:string_of("historyId")))
    local changeTypes = chilkat.StringTable.new()
    success = changeTypes:append("messagesAdded")
    if not success then
        print(changeTypes.last_error_text)
        return
    end

    success = changeTypes:append("messagesDeleted")
    if not success then
        print(changeTypes.last_error_text)
        return
    end

    success = changeTypes:append("labelsAdded")
    if not success then
        print(changeTypes.last_error_text)
        return
    end

    success = changeTypes:append("labelsRemoved")
    if not success then
        print(changeTypes.last_error_text)
        return
    end

    local record = chilkat.JsonObject.new()
    local eventPath = chilkat.StringBuilder.new()
    while more do
        url:set_string(baseUrl:get_as_string())
        url:append("&pageToken=")
        url:append(http:url_encode(pageToken))
        success = http:http_no_body("GET", url:get_as_string(), resp)
        if resp.status_code == 404 then
            print("History checkpoint expired. Rebuilding the cache.")
            fullSync = true
            more = false
        else
            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 h = 0
            while h < reply:size_of_array("history") do
                reply.i = h
                success = reply:object_of2("history[i]", record)
                if not success then
                    print(reply.last_error_text)
                    return
                end

                local t = 0
                while t < changeTypes.count do
                    local j = 0
                    while j < record:size_of_array(changeTypes:string_at(t)) do
                        eventPath:set_string(changeTypes:string_at(t))
                        eventPath:append("[")
                        eventPath:append_int(j)
                        eventPath:append("].message.id")
                        success = ids:add_int(record:string_of(eventPath:get_as_string()), 1)
                        if not success then
                            print(ids.last_error_text)
                            return
                        end

                        j = j + 1
                    end

                    t = t + 1
                end

                h = h + 1
            end

            pageToken = ""
            if reply:json_type_of("nextPageToken") == 1 then
                pageToken = reply:string_of("nextPageToken")
            end

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

                checkpoint = reply:string_of("historyId")
            end
        end
    end
end

if fullSync then
    -- Rebuild in memory. Any failure leaves the committed file available for a retry.
    ids:clear()
    state:clear()
    success = state:update_string("emailAddress", mailbox)
    if not success then
        print(state.last_error_text)
        return
    end

    success = state:update_new_object("messages")
    if not success then
        print(state.last_error_text)
        return
    end

    checkpoint = baseline
    pageToken = ""
    more = true
    while more do
        url:set_string("https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=500&includeSpamTrash=true&pageToken=")
        url:append(http:url_encode(pageToken))
        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

        local m = 0
        while m < reply:size_of_array("messages") do
            reply.i = m
            success = ids:add_int(reply:string_of("messages[i].id"), 1)
            if not success then
                print(ids.last_error_text)
                return
            end

            m = m + 1
        end

        pageToken = ""
        if reply:json_type_of("nextPageToken") == 1 then
            pageToken = reply:string_of("nextPageToken")
        end

        more = pageToken ~= ""
    end
end

local messages = chilkat.JsonObject.new()
success = state:object_of2("messages", messages)
if not success then
    print(state.last_error_text)
    return
end

-- Message refresh order is unimportant. GetKeys appends keys to this new table.
local messageIds = chilkat.StringTable.new()
success = ids:get_keys(messageIds)
if not success then
    print(ids.last_error_text)
    return
end

local cachedMessage = chilkat.JsonObject.new()
local i = 0
while i < messageIds.count do
    local messageId = messageIds:string_at(i)
    url:set_string("https://gmail.googleapis.com/gmail/v1/users/me/messages/")
    url:append(http:url_encode(messageId))
    url:append("?format=minimal&fields=id,threadId,labelIds")
    success = http:http_no_body("GET", url:get_as_string(), resp)
    if resp.status_code == 404 then
        if messages:has_member(messageId) then
            success = messages:delete(messageId)
            if not success then
                print(messages.last_error_text)
                return
            end
        end

        print("Removed from cache: " .. messageId)
    else
        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

        if not reply:string_of_equals("id", messageId, true) then
            print("Unexpected message ID in the response.")
            return
        end

        success = messages:update_new_object(messageId)
        if not success then
            print(messages.last_error_text)
            return
        end

        success = messages:object_of2(messageId, cachedMessage)
        if not success then
            print(messages.last_error_text)
            return
        end

        success = cachedMessage:load(reply:emit())
        if not success then
            print(cachedMessage.last_error_text)
            return
        end

        print("Cached message: " .. messageId)
    end

    i = i + 1
end

success = state:update_string("historyId", checkpoint)
if not success then
    print(state.last_error_text)
    return
end

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

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

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

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

print("Synchronization committed. Cached messages: " .. messages.size)
print("Saved history ID: " .. checkpoint)