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

Ruby
require 'chilkat'

success = false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

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("access_token") != 1) or (token.StringOfEquals("access_token","",true) == true))
    print "An OAuth access token is required." + "\n";
    exit
end

http = Chilkat::CkHttp.new()
http.put_RequireSslCertVerify(true)
http.put_AuthToken(token.stringOf("access_token"))
resp = Chilkat::CkHttpResponse.new()
reply = Chilkat::CkJsonObject.new()
files = Chilkat::CkFileAccess.new()
#  Recover the previous complete file if a run stopped during replacement.
fileStatus = files.FileExists3("gmail-sync.json")
if (fileStatus < 0)
    print "Could not inspect gmail-sync.json." + "\n";
    exit
end

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

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

        fileStatus = 1
    end

end

state = Chilkat::CkJsonObject.new()
if (fileStatus == 1)
    success = state.LoadFile("gmail-sync.json")
    if (success != true)
        print "Could not read the existing synchronization state." + "\n";
        exit
    end

    if ((state.JsonTypeOf("historyId") != 1) or (state.JsonTypeOf("messages") != 3) or (state.JsonTypeOf("emailAddress") != 1))
        print "The synchronization state is incomplete. Restore its previous complete copy." + "\n";
        exit
    end

end

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

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

mailbox = reply.stringOf("emailAddress")
baseline = reply.stringOf("historyId")
if (fileStatus == 1)
    if (state.StringOfEquals("emailAddress",mailbox,false) != true)
        print "Use a separate synchronization file for this mailbox." + "\n";
        exit
    end

end

fullSync = fileStatus == 0
checkpoint = baseline
#  A hashtable collects each changed ID once, even across multiple history records.
ids = Chilkat::CkHashtable.new()
baseUrl = Chilkat::CkStringBuilder.new()
url = Chilkat::CkStringBuilder.new()
pageToken = ""
more = true

if (fullSync != true)
    baseUrl.SetString("https://gmail.googleapis.com/gmail/v1/users/me/history?maxResults=500&startHistoryId=")
    baseUrl.Append(http.urlEncode(state.stringOf("historyId")))
    changeTypes = Chilkat::CkStringTable.new()
    success = changeTypes.Append("messagesAdded")
    if (success != true)
        print changeTypes.lastErrorText() + "\n";
        exit
    end

    success = changeTypes.Append("messagesDeleted")
    if (success != true)
        print changeTypes.lastErrorText() + "\n";
        exit
    end

    success = changeTypes.Append("labelsAdded")
    if (success != true)
        print changeTypes.lastErrorText() + "\n";
        exit
    end

    success = changeTypes.Append("labelsRemoved")
    if (success != true)
        print changeTypes.lastErrorText() + "\n";
        exit
    end

    record = Chilkat::CkJsonObject.new()
    eventPath = Chilkat::CkStringBuilder.new()
    while (more == true)
        url.SetString(baseUrl.getAsString())
        url.Append("&pageToken=")
        url.Append(http.urlEncode(pageToken))
        success = http.HttpNoBody("GET",url.getAsString(),resp)
        if (resp.get_StatusCode() == 404)
            print "History checkpoint expired. Rebuilding the cache." + "\n";
            fullSync = true
            more = false
        else
            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

            h = 0
            while (h < reply.SizeOfArray("history"))
                reply.put_I(h)
                success = reply.ObjectOf2("history[i]",record)
                if (success != true)
                    print reply.lastErrorText() + "\n";
                    exit
                end

                t = 0
                while (t < changeTypes.get_Count())
                    j = 0
                    while (j < record.SizeOfArray(changeTypes.stringAt(t)))
                        eventPath.SetString(changeTypes.stringAt(t))
                        eventPath.Append("[")
                        eventPath.AppendInt(j)
                        eventPath.Append("].message.id")
                        success = ids.AddInt(record.stringOf(eventPath.getAsString()),1)
                        if (success != true)
                            print ids.lastErrorText() + "\n";
                            exit
                        end

                        j = j + 1
                    end
                    t = t + 1
                end
                h = h + 1
            end
            pageToken = ""
            if (reply.JsonTypeOf("nextPageToken") == 1)
                pageToken = reply.stringOf("nextPageToken")
            end

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

                checkpoint = reply.stringOf("historyId")
            end

        end

    end
end

if (fullSync == true)
    #  Rebuild in memory. Any failure leaves the committed file available for a retry.
    ids.Clear()
    state.Clear()
    success = state.UpdateString("emailAddress",mailbox)
    if (success != true)
        print state.lastErrorText() + "\n";
        exit
    end

    success = state.UpdateNewObject("messages")
    if (success != true)
        print state.lastErrorText() + "\n";
        exit
    end

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

        m = 0
        while (m < reply.SizeOfArray("messages"))
            reply.put_I(m)
            success = ids.AddInt(reply.stringOf("messages[i].id"),1)
            if (success != true)
                print ids.lastErrorText() + "\n";
                exit
            end

            m = m + 1
        end
        pageToken = ""
        if (reply.JsonTypeOf("nextPageToken") == 1)
            pageToken = reply.stringOf("nextPageToken")
        end

        more = pageToken != ""
    end
end

messages = Chilkat::CkJsonObject.new()
success = state.ObjectOf2("messages",messages)
if (success != true)
    print state.lastErrorText() + "\n";
    exit
end

#  Message refresh order is unimportant. GetKeys appends keys to this new table.
messageIds = Chilkat::CkStringTable.new()
success = ids.GetKeys(messageIds)
if (success != true)
    print ids.lastErrorText() + "\n";
    exit
end

cachedMessage = Chilkat::CkJsonObject.new()
i = 0
while (i < messageIds.get_Count())
    messageId = messageIds.stringAt(i)
    url.SetString("https://gmail.googleapis.com/gmail/v1/users/me/messages/")
    url.Append(http.urlEncode(messageId))
    url.Append("?format=minimal&fields=id,threadId,labelIds")
    success = http.HttpNoBody("GET",url.getAsString(),resp)
    if (resp.get_StatusCode() == 404)
        if (messages.HasMember(messageId) == true)
            success = messages.Delete(messageId)
            if (success != true)
                print messages.lastErrorText() + "\n";
                exit
            end

        end

        print "Removed from cache: " + messageId + "\n";
    else
        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.StringOfEquals("id",messageId,true) != true)
            print "Unexpected message ID in the response." + "\n";
            exit
        end

        success = messages.UpdateNewObject(messageId)
        if (success != true)
            print messages.lastErrorText() + "\n";
            exit
        end

        success = messages.ObjectOf2(messageId,cachedMessage)
        if (success != true)
            print messages.lastErrorText() + "\n";
            exit
        end

        success = cachedMessage.Load(reply.emit())
        if (success != true)
            print cachedMessage.lastErrorText() + "\n";
            exit
        end

        print "Cached message: " + messageId + "\n";
    end

    i = i + 1
end
success = state.UpdateString("historyId",checkpoint)
if (success != true)
    print state.lastErrorText() + "\n";
    exit
end

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

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

    end

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

end

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

print "Synchronization committed. Cached messages: " + messages.get_Size().to_s() + "\n";
print "Saved history ID: " + checkpoint + "\n";