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.
Chilkat B4X Downloads
Dim success As Boolean = False
' Assumes Chilkat is unlocked. See Global Unlock Sample.
Dim token As ChilkatJsonObject
token.Initialize
success = token.LoadFile("gmail-token.json")
If success <> True Then
Log("Could not read gmail-token.json from the private working directory.")
Return
End If
If (token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token", "", True) = True) Then
Log("An OAuth access token is required.")
Return
End If
Dim http As ChilkatHttp
http.Initialize("http")
http.RequireSslCertVerify = True
http.AuthToken = token.StringOf("access_token")
Dim resp As ChilkatHttpResponse
resp.Initialize
Dim reply As ChilkatJsonObject
reply.Initialize
Dim files As ChilkatFileAccess
files.Initialize
' Recover the previous complete file if a run stopped during replacement.
Dim fileStatus As Int = files.FileExists3("gmail-sync.json")
If fileStatus < 0 Then
Log("Could not inspect gmail-sync.json.")
Return
End If
If fileStatus = 0 Then
Dim backupStatus As Int = files.FileExists3("gmail-sync.json.previous")
If backupStatus < 0 Then
Log("Could not inspect the backup file.")
Return
End If
If backupStatus = 1 Then
success = files.FileRename("gmail-sync.json.previous", "gmail-sync.json")
If success <> True Then
Log("Could not restore the previous complete file.")
Return
End If
fileStatus = 1
End If
End If
Dim state As ChilkatJsonObject
state.Initialize
If fileStatus = 1 Then
success = state.LoadFile("gmail-sync.json")
If success <> True Then
Log("Could not read the existing synchronization state.")
Return
End If
If (state.JsonTypeOf("historyId") <> 1) Or (state.JsonTypeOf("messages") <> 3) Or (state.JsonTypeOf("emailAddress") <> 1) Then
Log("The synchronization state is incomplete. Restore its previous complete copy.")
Return
End If
End If
success = http.HttpNoBody("GET", "https://gmail.googleapis.com/gmail/v1/users/me/profile", resp)
If resp.StatusCode = 0 Then
Log("Gmail did not return an HTTP response.")
Return
End If
If (success <> True) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300) Then
Log("Gmail HTTP " & resp.StatusCode)
success = reply.Load(resp.BodyStr)
If success = True Then
Log(reply.StringOf("error.message"))
End If
Return
End If
success = reply.Load(resp.BodyStr)
If success <> True Then
Log("Expected a Gmail JSON response.")
Return
End If
If (reply.JsonTypeOf("emailAddress") <> 1) Or (reply.StringOfEquals("emailAddress", "", True) = True) Then
Log("Expected emailAddress in the response.")
Return
End If
If (reply.JsonTypeOf("historyId") <> 1) Or (reply.StringOfEquals("historyId", "", True) = True) Then
Log("Expected historyId in the response.")
Return
End If
Dim mailbox As String = reply.StringOf("emailAddress")
Dim baseline As String = reply.StringOf("historyId")
If fileStatus = 1 Then
If state.StringOfEquals("emailAddress", mailbox, False) <> True Then
Log("Use a separate synchronization file for this mailbox.")
Return
End If
End If
Dim fullSync As Boolean = fileStatus = 0
Dim checkpoint As String = baseline
' A hashtable collects each changed ID once, even across multiple history records.
Dim ids As ChilkatHashtable
ids.Initialize
Dim baseUrl As ChilkatStringBuilder
baseUrl.Initialize
Dim url As ChilkatStringBuilder
url.Initialize
Dim pageToken As String = ""
Dim more As Boolean = True
If fullSync <> True Then
baseUrl.SetString("https://gmail.googleapis.com/gmail/v1/users/me/history?maxResults=500&startHistoryId=")
baseUrl.Append(http.UrlEncode(state.StringOf("historyId")))
Dim changeTypes As ChilkatStringTable
changeTypes.Initialize
success = changeTypes.Append("messagesAdded")
If success <> True Then
Log(changeTypes.LastErrorText)
Return
End If
success = changeTypes.Append("messagesDeleted")
If success <> True Then
Log(changeTypes.LastErrorText)
Return
End If
success = changeTypes.Append("labelsAdded")
If success <> True Then
Log(changeTypes.LastErrorText)
Return
End If
success = changeTypes.Append("labelsRemoved")
If success <> True Then
Log(changeTypes.LastErrorText)
Return
End If
Dim record As ChilkatJsonObject
record.Initialize
Dim eventPath As ChilkatStringBuilder
eventPath.Initialize
Do While (more = True)
url.SetString(baseUrl.GetAsString)
url.Append("&pageToken=")
url.Append(http.UrlEncode(pageToken))
success = http.HttpNoBody("GET", url.GetAsString, resp)
If resp.StatusCode = 404 Then
Log("History checkpoint expired. Rebuilding the cache.")
fullSync = True
more = False
Else
If resp.StatusCode = 0 Then
Log("Gmail did not return an HTTP response.")
Return
End If
If (success <> True) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300) Then
Log("Gmail HTTP " & resp.StatusCode)
success = reply.Load(resp.BodyStr)
If success = True Then
Log(reply.StringOf("error.message"))
End If
Return
End If
success = reply.Load(resp.BodyStr)
If success <> True Then
Log("Expected a Gmail JSON response.")
Return
End If
Dim h As Int = 0
Do While (h < reply.SizeOfArray("history"))
reply.I = h
success = reply.ObjectOf2("history[i]", record)
If success <> True Then
Log(reply.LastErrorText)
Return
End If
Dim t As Int = 0
Do While (t < changeTypes.Count)
Dim j As Int = 0
Do 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 Then
Log(ids.LastErrorText)
Return
End If
j = j + 1
Loop
t = t + 1
Loop
h = h + 1
Loop
pageToken = ""
If reply.JsonTypeOf("nextPageToken") = 1 Then
pageToken = reply.StringOf("nextPageToken")
End If
more = pageToken <> ""
If more <> True Then
If (reply.JsonTypeOf("historyId") <> 1) Or (reply.StringOfEquals("historyId", "", True) = True) Then
Log("Expected historyId in the response.")
Return
End If
checkpoint = reply.StringOf("historyId")
End If
End If
Loop
End If
If fullSync = True Then
' 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 Then
Log(state.LastErrorText)
Return
End If
success = state.UpdateNewObject("messages")
If success <> True Then
Log(state.LastErrorText)
Return
End If
checkpoint = baseline
pageToken = ""
more = True
Do 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.StatusCode = 0 Then
Log("Gmail did not return an HTTP response.")
Return
End If
If (success <> True) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300) Then
Log("Gmail HTTP " & resp.StatusCode)
success = reply.Load(resp.BodyStr)
If success = True Then
Log(reply.StringOf("error.message"))
End If
Return
End If
success = reply.Load(resp.BodyStr)
If success <> True Then
Log("Expected a Gmail JSON response.")
Return
End If
Dim m As Int = 0
Do While (m < reply.SizeOfArray("messages"))
reply.I = m
success = ids.AddInt(reply.StringOf("messages[i].id"), 1)
If success <> True Then
Log(ids.LastErrorText)
Return
End If
m = m + 1
Loop
pageToken = ""
If reply.JsonTypeOf("nextPageToken") = 1 Then
pageToken = reply.StringOf("nextPageToken")
End If
more = pageToken <> ""
Loop
End If
Dim messages As ChilkatJsonObject
messages.Initialize
success = state.ObjectOf2("messages", messages)
If success <> True Then
Log(state.LastErrorText)
Return
End If
' Message refresh order is unimportant. GetKeys appends keys to this new table.
Dim messageIds As ChilkatStringTable
messageIds.Initialize
success = ids.GetKeys(messageIds)
If success <> True Then
Log(ids.LastErrorText)
Return
End If
Dim cachedMessage As ChilkatJsonObject
cachedMessage.Initialize
Dim i As Int = 0
Do While (i < messageIds.Count)
Dim messageId As String = 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.StatusCode = 404 Then
If messages.HasMember(messageId) = True Then
success = messages.Delete(messageId)
If success <> True Then
Log(messages.LastErrorText)
Return
End If
End If
Log("Removed from cache: " & messageId)
Else
If resp.StatusCode = 0 Then
Log("Gmail did not return an HTTP response.")
Return
End If
If (success <> True) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300) Then
Log("Gmail HTTP " & resp.StatusCode)
success = reply.Load(resp.BodyStr)
If success = True Then
Log(reply.StringOf("error.message"))
End If
Return
End If
success = reply.Load(resp.BodyStr)
If success <> True Then
Log("Expected a Gmail JSON response.")
Return
End If
If reply.StringOfEquals("id", messageId, True) <> True Then
Log("Unexpected message ID in the response.")
Return
End If
success = messages.UpdateNewObject(messageId)
If success <> True Then
Log(messages.LastErrorText)
Return
End If
success = messages.ObjectOf2(messageId, cachedMessage)
If success <> True Then
Log(messages.LastErrorText)
Return
End If
success = cachedMessage.Load(reply.Emit)
If success <> True Then
Log(cachedMessage.LastErrorText)
Return
End If
Log("Cached message: " & messageId)
End If
i = i + 1
Loop
success = state.UpdateString("historyId", checkpoint)
If success <> True Then
Log(state.LastErrorText)
Return
End If
' Prepare the complete replacement before moving the last committed file.
success = state.WriteFile("gmail-sync.json.new")
If success <> True Then
Log("Could not write the replacement file.")
Return
End If
If files.FileExists("gmail-sync.json") = True Then
If files.FileExists("gmail-sync.json.previous") = True Then
success = files.FileDelete("gmail-sync.json.previous")
If success <> True Then
Log("Could not rotate the previous backup.")
Return
End If
End If
success = files.FileRename("gmail-sync.json", "gmail-sync.json.previous")
If success <> True Then
Log("Could not retain the previous complete file.")
Return
End If
End If
success = files.FileRename("gmail-sync.json.new", "gmail-sync.json")
If success <> True Then
Log("Could not commit the replacement. The previous complete file is retained.")
Return
End If
Log("Synchronization committed. Cached messages: " & messages.Size)
Log("Saved history ID: " & checkpoint)