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