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

PowerBuilder
integer li_rc
long li_Success
oleobject loo_Token
oleobject loo_Http
oleobject loo_Resp
oleobject loo_Reply
oleobject loo_Files
long li_FileStatus
long li_BackupStatus
oleobject loo_State
string ls_Mailbox
string ls_Baseline
long li_FullSync
string ls_Checkpoint
oleobject loo_Ids
oleobject loo_BaseUrl
oleobject loo_Url
string ls_PageToken
long li_More
oleobject loo_ChangeTypes
oleobject loo_Record
oleobject loo_EventPath
long h
long t
long j
long m
oleobject loo_Messages
oleobject loo_MessageIds
oleobject loo_CachedMessage
long i
string ls_MessageId

li_Success = 0

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

loo_Token = create oleobject
li_rc = loo_Token.ConnectToNewObject("Chilkat.JsonObject")
if li_rc < 0 then
    destroy loo_Token
    MessageBox("Error","Connecting to COM object failed")
    return
end if
li_Success = loo_Token.LoadFile("gmail-token.json")
if li_Success <> 1 then
    Write-Debug "Could not read gmail-token.json from the private working directory."
    destroy loo_Token
    return
end if

if (loo_Token.JsonTypeOf("access_token") <> 1) OR (loo_Token.StringOfEquals("access_token","",1) = 1) then
    Write-Debug "An OAuth access token is required."
    destroy loo_Token
    return
end if

loo_Http = create oleobject
li_rc = loo_Http.ConnectToNewObject("Chilkat.Http")

loo_Http.RequireSslCertVerify = 1
loo_Http.AuthToken = loo_Token.StringOf("access_token")
loo_Resp = create oleobject
li_rc = loo_Resp.ConnectToNewObject("Chilkat.HttpResponse")

loo_Reply = create oleobject
li_rc = loo_Reply.ConnectToNewObject("Chilkat.JsonObject")

loo_Files = create oleobject
li_rc = loo_Files.ConnectToNewObject("Chilkat.FileAccess")

//  Recover the previous complete file if a run stopped during replacement.
li_FileStatus = loo_Files.FileExists3("gmail-sync.json")
if li_FileStatus < 0 then
    Write-Debug "Could not inspect gmail-sync.json."
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    destroy loo_Files
    return
end if

if li_FileStatus = 0 then
    li_BackupStatus = loo_Files.FileExists3("gmail-sync.json.previous")
    if li_BackupStatus < 0 then
        Write-Debug "Could not inspect the backup file."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Reply
        destroy loo_Files
        return
    end if

    if li_BackupStatus = 1 then
        li_Success = loo_Files.FileRename("gmail-sync.json.previous","gmail-sync.json")
        if li_Success <> 1 then
            Write-Debug "Could not restore the previous complete file."
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Reply
            destroy loo_Files
            return
        end if

        li_FileStatus = 1
    end if

end if

loo_State = create oleobject
li_rc = loo_State.ConnectToNewObject("Chilkat.JsonObject")

if li_FileStatus = 1 then
    li_Success = loo_State.LoadFile("gmail-sync.json")
    if li_Success <> 1 then
        Write-Debug "Could not read the existing synchronization state."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Reply
        destroy loo_Files
        destroy loo_State
        return
    end if

    if (loo_State.JsonTypeOf("historyId") <> 1) OR (loo_State.JsonTypeOf("messages") <> 3) OR (loo_State.JsonTypeOf("emailAddress") <> 1) then
        Write-Debug "The synchronization state is incomplete. Restore its previous complete copy."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Reply
        destroy loo_Files
        destroy loo_State
        return
    end if

end if

li_Success = loo_Http.HttpNoBody("GET","https://gmail.googleapis.com/gmail/v1/users/me/profile",loo_Resp)
if loo_Resp.StatusCode = 0 then
    Write-Debug "Gmail did not return an HTTP response."
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    destroy loo_Files
    destroy loo_State
    return
end if

if (li_Success <> 1) OR (loo_Resp.StatusCode < 200) OR (loo_Resp.StatusCode >= 300) then
    Write-Debug "Gmail HTTP " + string(loo_Resp.StatusCode)
    li_Success = loo_Reply.Load(loo_Resp.BodyStr)
    if li_Success = 1 then
        Write-Debug loo_Reply.StringOf("error.message")
    end if

    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    destroy loo_Files
    destroy loo_State
    return
end if

li_Success = loo_Reply.Load(loo_Resp.BodyStr)
if li_Success <> 1 then
    Write-Debug "Expected a Gmail JSON response."
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    destroy loo_Files
    destroy loo_State
    return
end if

if (loo_Reply.JsonTypeOf("emailAddress") <> 1) OR (loo_Reply.StringOfEquals("emailAddress","",1) = 1) then
    Write-Debug "Expected emailAddress in the response."
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    destroy loo_Files
    destroy loo_State
    return
end if

if (loo_Reply.JsonTypeOf("historyId") <> 1) OR (loo_Reply.StringOfEquals("historyId","",1) = 1) then
    Write-Debug "Expected historyId in the response."
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    destroy loo_Files
    destroy loo_State
    return
end if

ls_Mailbox = loo_Reply.StringOf("emailAddress")
ls_Baseline = loo_Reply.StringOf("historyId")
if li_FileStatus = 1 then
    if loo_State.StringOfEquals("emailAddress",ls_Mailbox,0) <> 1 then
        Write-Debug "Use a separate synchronization file for this mailbox."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Reply
        destroy loo_Files
        destroy loo_State
        return
    end if

end if

li_FullSync = li_FileStatus = 0
ls_Checkpoint = ls_Baseline
//  A hashtable collects each changed ID once, even across multiple history records.
loo_Ids = create oleobject
li_rc = loo_Ids.ConnectToNewObject("Chilkat.Hashtable")

loo_BaseUrl = create oleobject
li_rc = loo_BaseUrl.ConnectToNewObject("Chilkat.StringBuilder")

loo_Url = create oleobject
li_rc = loo_Url.ConnectToNewObject("Chilkat.StringBuilder")

ls_PageToken = ""
li_More = 1

if li_FullSync <> 1 then
    loo_BaseUrl.SetString("https://gmail.googleapis.com/gmail/v1/users/me/history?maxResults=500&startHistoryId=")
    loo_BaseUrl.Append(loo_Http.UrlEncode(loo_State.StringOf("historyId")))
    loo_ChangeTypes = create oleobject
    li_rc = loo_ChangeTypes.ConnectToNewObject("Chilkat.StringTable")

    li_Success = loo_ChangeTypes.Append("messagesAdded")
    if li_Success <> 1 then
        Write-Debug loo_ChangeTypes.LastErrorText
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Reply
        destroy loo_Files
        destroy loo_State
        destroy loo_Ids
        destroy loo_BaseUrl
        destroy loo_Url
        destroy loo_ChangeTypes
        return
    end if

    li_Success = loo_ChangeTypes.Append("messagesDeleted")
    if li_Success <> 1 then
        Write-Debug loo_ChangeTypes.LastErrorText
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Reply
        destroy loo_Files
        destroy loo_State
        destroy loo_Ids
        destroy loo_BaseUrl
        destroy loo_Url
        destroy loo_ChangeTypes
        return
    end if

    li_Success = loo_ChangeTypes.Append("labelsAdded")
    if li_Success <> 1 then
        Write-Debug loo_ChangeTypes.LastErrorText
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Reply
        destroy loo_Files
        destroy loo_State
        destroy loo_Ids
        destroy loo_BaseUrl
        destroy loo_Url
        destroy loo_ChangeTypes
        return
    end if

    li_Success = loo_ChangeTypes.Append("labelsRemoved")
    if li_Success <> 1 then
        Write-Debug loo_ChangeTypes.LastErrorText
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Reply
        destroy loo_Files
        destroy loo_State
        destroy loo_Ids
        destroy loo_BaseUrl
        destroy loo_Url
        destroy loo_ChangeTypes
        return
    end if

    loo_Record = create oleobject
    li_rc = loo_Record.ConnectToNewObject("Chilkat.JsonObject")

    loo_EventPath = create oleobject
    li_rc = loo_EventPath.ConnectToNewObject("Chilkat.StringBuilder")

    do while (li_More = 1)
        loo_Url.SetString(loo_BaseUrl.GetAsString())
        loo_Url.Append("&pageToken=")
        loo_Url.Append(loo_Http.UrlEncode(ls_PageToken))
        li_Success = loo_Http.HttpNoBody("GET",loo_Url.GetAsString(),loo_Resp)
        if loo_Resp.StatusCode = 404 then
            Write-Debug "History checkpoint expired. Rebuilding the cache."
            li_FullSync = 1
            li_More = 0
        else
            if loo_Resp.StatusCode = 0 then
                Write-Debug "Gmail did not return an HTTP response."
                destroy loo_Token
                destroy loo_Http
                destroy loo_Resp
                destroy loo_Reply
                destroy loo_Files
                destroy loo_State
                destroy loo_Ids
                destroy loo_BaseUrl
                destroy loo_Url
                destroy loo_ChangeTypes
                destroy loo_Record
                destroy loo_EventPath
                return
            end if

            if (li_Success <> 1) OR (loo_Resp.StatusCode < 200) OR (loo_Resp.StatusCode >= 300) then
                Write-Debug "Gmail HTTP " + string(loo_Resp.StatusCode)
                li_Success = loo_Reply.Load(loo_Resp.BodyStr)
                if li_Success = 1 then
                    Write-Debug loo_Reply.StringOf("error.message")
                end if

                destroy loo_Token
                destroy loo_Http
                destroy loo_Resp
                destroy loo_Reply
                destroy loo_Files
                destroy loo_State
                destroy loo_Ids
                destroy loo_BaseUrl
                destroy loo_Url
                destroy loo_ChangeTypes
                destroy loo_Record
                destroy loo_EventPath
                return
            end if

            li_Success = loo_Reply.Load(loo_Resp.BodyStr)
            if li_Success <> 1 then
                Write-Debug "Expected a Gmail JSON response."
                destroy loo_Token
                destroy loo_Http
                destroy loo_Resp
                destroy loo_Reply
                destroy loo_Files
                destroy loo_State
                destroy loo_Ids
                destroy loo_BaseUrl
                destroy loo_Url
                destroy loo_ChangeTypes
                destroy loo_Record
                destroy loo_EventPath
                return
            end if

            h = 0
            do while (h < loo_Reply.SizeOfArray("history"))
                loo_Reply.I = h
                li_Success = loo_Reply.ObjectOf2("history[i]",loo_Record)
                if li_Success <> 1 then
                    Write-Debug loo_Reply.LastErrorText
                    destroy loo_Token
                    destroy loo_Http
                    destroy loo_Resp
                    destroy loo_Reply
                    destroy loo_Files
                    destroy loo_State
                    destroy loo_Ids
                    destroy loo_BaseUrl
                    destroy loo_Url
                    destroy loo_ChangeTypes
                    destroy loo_Record
                    destroy loo_EventPath
                    return
                end if

                t = 0
                do while (t < loo_ChangeTypes.Count)
                    j = 0
                    do while (j < loo_Record.SizeOfArray(loo_ChangeTypes.StringAt(t)))
                        loo_EventPath.SetString(loo_ChangeTypes.StringAt(t))
                        loo_EventPath.Append("[")
                        loo_EventPath.AppendInt(j)
                        loo_EventPath.Append("].message.id")
                        li_Success = loo_Ids.AddInt(loo_Record.StringOf(loo_EventPath.GetAsString()),1)
                        if li_Success <> 1 then
                            Write-Debug loo_Ids.LastErrorText
                            destroy loo_Token
                            destroy loo_Http
                            destroy loo_Resp
                            destroy loo_Reply
                            destroy loo_Files
                            destroy loo_State
                            destroy loo_Ids
                            destroy loo_BaseUrl
                            destroy loo_Url
                            destroy loo_ChangeTypes
                            destroy loo_Record
                            destroy loo_EventPath
                            return
                        end if

                        j = j + 1
                    loop
                    t = t + 1
                loop
                h = h + 1
            loop
            ls_PageToken = ""
            if loo_Reply.JsonTypeOf("nextPageToken") = 1 then
                ls_PageToken = loo_Reply.StringOf("nextPageToken")
            end if

            li_More = ls_PageToken <> ""
            if li_More <> 1 then
                if (loo_Reply.JsonTypeOf("historyId") <> 1) OR (loo_Reply.StringOfEquals("historyId","",1) = 1) then
                    Write-Debug "Expected historyId in the response."
                    destroy loo_Token
                    destroy loo_Http
                    destroy loo_Resp
                    destroy loo_Reply
                    destroy loo_Files
                    destroy loo_State
                    destroy loo_Ids
                    destroy loo_BaseUrl
                    destroy loo_Url
                    destroy loo_ChangeTypes
                    destroy loo_Record
                    destroy loo_EventPath
                    return
                end if

                ls_Checkpoint = loo_Reply.StringOf("historyId")
            end if

        end if

    loop
end if

if li_FullSync = 1 then
    //  Rebuild in memory. Any failure leaves the committed file available for a retry.
    loo_Ids.Clear()
    loo_State.Clear()
    li_Success = loo_State.UpdateString("emailAddress",ls_Mailbox)
    if li_Success <> 1 then
        Write-Debug loo_State.LastErrorText
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Reply
        destroy loo_Files
        destroy loo_State
        destroy loo_Ids
        destroy loo_BaseUrl
        destroy loo_Url
        destroy loo_ChangeTypes
        destroy loo_Record
        destroy loo_EventPath
        return
    end if

    li_Success = loo_State.UpdateNewObject("messages")
    if li_Success <> 1 then
        Write-Debug loo_State.LastErrorText
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Reply
        destroy loo_Files
        destroy loo_State
        destroy loo_Ids
        destroy loo_BaseUrl
        destroy loo_Url
        destroy loo_ChangeTypes
        destroy loo_Record
        destroy loo_EventPath
        return
    end if

    ls_Checkpoint = ls_Baseline
    ls_PageToken = ""
    li_More = 1
    do while (li_More = 1)
        loo_Url.SetString("https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=500&includeSpamTrash=true&pageToken=")
        loo_Url.Append(loo_Http.UrlEncode(ls_PageToken))
        li_Success = loo_Http.HttpNoBody("GET",loo_Url.GetAsString(),loo_Resp)
        if loo_Resp.StatusCode = 0 then
            Write-Debug "Gmail did not return an HTTP response."
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Reply
            destroy loo_Files
            destroy loo_State
            destroy loo_Ids
            destroy loo_BaseUrl
            destroy loo_Url
            destroy loo_ChangeTypes
            destroy loo_Record
            destroy loo_EventPath
            return
        end if

        if (li_Success <> 1) OR (loo_Resp.StatusCode < 200) OR (loo_Resp.StatusCode >= 300) then
            Write-Debug "Gmail HTTP " + string(loo_Resp.StatusCode)
            li_Success = loo_Reply.Load(loo_Resp.BodyStr)
            if li_Success = 1 then
                Write-Debug loo_Reply.StringOf("error.message")
            end if

            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Reply
            destroy loo_Files
            destroy loo_State
            destroy loo_Ids
            destroy loo_BaseUrl
            destroy loo_Url
            destroy loo_ChangeTypes
            destroy loo_Record
            destroy loo_EventPath
            return
        end if

        li_Success = loo_Reply.Load(loo_Resp.BodyStr)
        if li_Success <> 1 then
            Write-Debug "Expected a Gmail JSON response."
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Reply
            destroy loo_Files
            destroy loo_State
            destroy loo_Ids
            destroy loo_BaseUrl
            destroy loo_Url
            destroy loo_ChangeTypes
            destroy loo_Record
            destroy loo_EventPath
            return
        end if

        m = 0
        do while (m < loo_Reply.SizeOfArray("messages"))
            loo_Reply.I = m
            li_Success = loo_Ids.AddInt(loo_Reply.StringOf("messages[i].id"),1)
            if li_Success <> 1 then
                Write-Debug loo_Ids.LastErrorText
                destroy loo_Token
                destroy loo_Http
                destroy loo_Resp
                destroy loo_Reply
                destroy loo_Files
                destroy loo_State
                destroy loo_Ids
                destroy loo_BaseUrl
                destroy loo_Url
                destroy loo_ChangeTypes
                destroy loo_Record
                destroy loo_EventPath
                return
            end if

            m = m + 1
        loop
        ls_PageToken = ""
        if loo_Reply.JsonTypeOf("nextPageToken") = 1 then
            ls_PageToken = loo_Reply.StringOf("nextPageToken")
        end if

        li_More = ls_PageToken <> ""
    loop
end if

loo_Messages = create oleobject
li_rc = loo_Messages.ConnectToNewObject("Chilkat.JsonObject")

li_Success = loo_State.ObjectOf2("messages",loo_Messages)
if li_Success <> 1 then
    Write-Debug loo_State.LastErrorText
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    destroy loo_Files
    destroy loo_State
    destroy loo_Ids
    destroy loo_BaseUrl
    destroy loo_Url
    destroy loo_ChangeTypes
    destroy loo_Record
    destroy loo_EventPath
    destroy loo_Messages
    return
end if

//  Message refresh order is unimportant. GetKeys appends keys to this new table.
loo_MessageIds = create oleobject
li_rc = loo_MessageIds.ConnectToNewObject("Chilkat.StringTable")

li_Success = loo_Ids.GetKeys(loo_MessageIds)
if li_Success <> 1 then
    Write-Debug loo_Ids.LastErrorText
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    destroy loo_Files
    destroy loo_State
    destroy loo_Ids
    destroy loo_BaseUrl
    destroy loo_Url
    destroy loo_ChangeTypes
    destroy loo_Record
    destroy loo_EventPath
    destroy loo_Messages
    destroy loo_MessageIds
    return
end if

loo_CachedMessage = create oleobject
li_rc = loo_CachedMessage.ConnectToNewObject("Chilkat.JsonObject")

i = 0
do while (i < loo_MessageIds.Count)
    ls_MessageId = loo_MessageIds.StringAt(i)
    loo_Url.SetString("https://gmail.googleapis.com/gmail/v1/users/me/messages/")
    loo_Url.Append(loo_Http.UrlEncode(ls_MessageId))
    loo_Url.Append("?format=minimal&fields=id,threadId,labelIds")
    li_Success = loo_Http.HttpNoBody("GET",loo_Url.GetAsString(),loo_Resp)
    if loo_Resp.StatusCode = 404 then
        if loo_Messages.HasMember(ls_MessageId) = 1 then
            li_Success = loo_Messages.Delete(ls_MessageId)
            if li_Success <> 1 then
                Write-Debug loo_Messages.LastErrorText
                destroy loo_Token
                destroy loo_Http
                destroy loo_Resp
                destroy loo_Reply
                destroy loo_Files
                destroy loo_State
                destroy loo_Ids
                destroy loo_BaseUrl
                destroy loo_Url
                destroy loo_ChangeTypes
                destroy loo_Record
                destroy loo_EventPath
                destroy loo_Messages
                destroy loo_MessageIds
                destroy loo_CachedMessage
                return
            end if

        end if

        Write-Debug "Removed from cache: " + ls_MessageId
    else
        if loo_Resp.StatusCode = 0 then
            Write-Debug "Gmail did not return an HTTP response."
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Reply
            destroy loo_Files
            destroy loo_State
            destroy loo_Ids
            destroy loo_BaseUrl
            destroy loo_Url
            destroy loo_ChangeTypes
            destroy loo_Record
            destroy loo_EventPath
            destroy loo_Messages
            destroy loo_MessageIds
            destroy loo_CachedMessage
            return
        end if

        if (li_Success <> 1) OR (loo_Resp.StatusCode < 200) OR (loo_Resp.StatusCode >= 300) then
            Write-Debug "Gmail HTTP " + string(loo_Resp.StatusCode)
            li_Success = loo_Reply.Load(loo_Resp.BodyStr)
            if li_Success = 1 then
                Write-Debug loo_Reply.StringOf("error.message")
            end if

            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Reply
            destroy loo_Files
            destroy loo_State
            destroy loo_Ids
            destroy loo_BaseUrl
            destroy loo_Url
            destroy loo_ChangeTypes
            destroy loo_Record
            destroy loo_EventPath
            destroy loo_Messages
            destroy loo_MessageIds
            destroy loo_CachedMessage
            return
        end if

        li_Success = loo_Reply.Load(loo_Resp.BodyStr)
        if li_Success <> 1 then
            Write-Debug "Expected a Gmail JSON response."
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Reply
            destroy loo_Files
            destroy loo_State
            destroy loo_Ids
            destroy loo_BaseUrl
            destroy loo_Url
            destroy loo_ChangeTypes
            destroy loo_Record
            destroy loo_EventPath
            destroy loo_Messages
            destroy loo_MessageIds
            destroy loo_CachedMessage
            return
        end if

        if loo_Reply.StringOfEquals("id",ls_MessageId,1) <> 1 then
            Write-Debug "Unexpected message ID in the response."
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Reply
            destroy loo_Files
            destroy loo_State
            destroy loo_Ids
            destroy loo_BaseUrl
            destroy loo_Url
            destroy loo_ChangeTypes
            destroy loo_Record
            destroy loo_EventPath
            destroy loo_Messages
            destroy loo_MessageIds
            destroy loo_CachedMessage
            return
        end if

        li_Success = loo_Messages.UpdateNewObject(ls_MessageId)
        if li_Success <> 1 then
            Write-Debug loo_Messages.LastErrorText
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Reply
            destroy loo_Files
            destroy loo_State
            destroy loo_Ids
            destroy loo_BaseUrl
            destroy loo_Url
            destroy loo_ChangeTypes
            destroy loo_Record
            destroy loo_EventPath
            destroy loo_Messages
            destroy loo_MessageIds
            destroy loo_CachedMessage
            return
        end if

        li_Success = loo_Messages.ObjectOf2(ls_MessageId,loo_CachedMessage)
        if li_Success <> 1 then
            Write-Debug loo_Messages.LastErrorText
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Reply
            destroy loo_Files
            destroy loo_State
            destroy loo_Ids
            destroy loo_BaseUrl
            destroy loo_Url
            destroy loo_ChangeTypes
            destroy loo_Record
            destroy loo_EventPath
            destroy loo_Messages
            destroy loo_MessageIds
            destroy loo_CachedMessage
            return
        end if

        li_Success = loo_CachedMessage.Load(loo_Reply.Emit())
        if li_Success <> 1 then
            Write-Debug loo_CachedMessage.LastErrorText
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Reply
            destroy loo_Files
            destroy loo_State
            destroy loo_Ids
            destroy loo_BaseUrl
            destroy loo_Url
            destroy loo_ChangeTypes
            destroy loo_Record
            destroy loo_EventPath
            destroy loo_Messages
            destroy loo_MessageIds
            destroy loo_CachedMessage
            return
        end if

        Write-Debug "Cached message: " + ls_MessageId
    end if

    i = i + 1
loop
li_Success = loo_State.UpdateString("historyId",ls_Checkpoint)
if li_Success <> 1 then
    Write-Debug loo_State.LastErrorText
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    destroy loo_Files
    destroy loo_State
    destroy loo_Ids
    destroy loo_BaseUrl
    destroy loo_Url
    destroy loo_ChangeTypes
    destroy loo_Record
    destroy loo_EventPath
    destroy loo_Messages
    destroy loo_MessageIds
    destroy loo_CachedMessage
    return
end if

//  Prepare the complete replacement before moving the last committed file.
li_Success = loo_State.WriteFile("gmail-sync.json.new")
if li_Success <> 1 then
    Write-Debug "Could not write the replacement file."
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    destroy loo_Files
    destroy loo_State
    destroy loo_Ids
    destroy loo_BaseUrl
    destroy loo_Url
    destroy loo_ChangeTypes
    destroy loo_Record
    destroy loo_EventPath
    destroy loo_Messages
    destroy loo_MessageIds
    destroy loo_CachedMessage
    return
end if

if loo_Files.FileExists("gmail-sync.json") = 1 then
    if loo_Files.FileExists("gmail-sync.json.previous") = 1 then
        li_Success = loo_Files.FileDelete("gmail-sync.json.previous")
        if li_Success <> 1 then
            Write-Debug "Could not rotate the previous backup."
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Reply
            destroy loo_Files
            destroy loo_State
            destroy loo_Ids
            destroy loo_BaseUrl
            destroy loo_Url
            destroy loo_ChangeTypes
            destroy loo_Record
            destroy loo_EventPath
            destroy loo_Messages
            destroy loo_MessageIds
            destroy loo_CachedMessage
            return
        end if

    end if

    li_Success = loo_Files.FileRename("gmail-sync.json","gmail-sync.json.previous")
    if li_Success <> 1 then
        Write-Debug "Could not retain the previous complete file."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Reply
        destroy loo_Files
        destroy loo_State
        destroy loo_Ids
        destroy loo_BaseUrl
        destroy loo_Url
        destroy loo_ChangeTypes
        destroy loo_Record
        destroy loo_EventPath
        destroy loo_Messages
        destroy loo_MessageIds
        destroy loo_CachedMessage
        return
    end if

end if

li_Success = loo_Files.FileRename("gmail-sync.json.new","gmail-sync.json")
if li_Success <> 1 then
    Write-Debug "Could not commit the replacement. The previous complete file is retained."
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Reply
    destroy loo_Files
    destroy loo_State
    destroy loo_Ids
    destroy loo_BaseUrl
    destroy loo_Url
    destroy loo_ChangeTypes
    destroy loo_Record
    destroy loo_EventPath
    destroy loo_Messages
    destroy loo_MessageIds
    destroy loo_CachedMessage
    return
end if

Write-Debug "Synchronization committed. Cached messages: " + string(loo_Messages.Size)
Write-Debug "Saved history ID: " + ls_Checkpoint


destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Reply
destroy loo_Files
destroy loo_State
destroy loo_Ids
destroy loo_BaseUrl
destroy loo_Url
destroy loo_ChangeTypes
destroy loo_Record
destroy loo_EventPath
destroy loo_Messages
destroy loo_MessageIds
destroy loo_CachedMessage