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 Classic ASP Downloads
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<%
success = 0
' Assumes Chilkat is unlocked. See Global Unlock Sample.
set token = Server.CreateObject("Chilkat.JsonObject")
success = token.LoadFile("gmail-token.json")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not read gmail-token.json from the private working directory.") & "</pre>"
Response.End
End If
If ((token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token","",1) = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "An OAuth access token is required.") & "</pre>"
Response.End
End If
set http = Server.CreateObject("Chilkat.Http")
http.RequireSslCertVerify = 1
http.AuthToken = token.StringOf("access_token")
set resp = Server.CreateObject("Chilkat.HttpResponse")
set reply = Server.CreateObject("Chilkat.JsonObject")
set files = Server.CreateObject("Chilkat.FileAccess")
' Recover the previous complete file if a run stopped during replacement.
fileStatus = files.FileExists3("gmail-sync.json")
If (fileStatus < 0) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not inspect gmail-sync.json.") & "</pre>"
Response.End
End If
If (fileStatus = 0) Then
backupStatus = files.FileExists3("gmail-sync.json.previous")
If (backupStatus < 0) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not inspect the backup file.") & "</pre>"
Response.End
End If
If (backupStatus = 1) Then
success = files.FileRename("gmail-sync.json.previous","gmail-sync.json")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not restore the previous complete file.") & "</pre>"
Response.End
End If
fileStatus = 1
End If
End If
set state = Server.CreateObject("Chilkat.JsonObject")
If (fileStatus = 1) Then
success = state.LoadFile("gmail-sync.json")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not read the existing synchronization state.") & "</pre>"
Response.End
End If
If ((state.JsonTypeOf("historyId") <> 1) Or (state.JsonTypeOf("messages") <> 3) Or (state.JsonTypeOf("emailAddress") <> 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "The synchronization state is incomplete. Restore its previous complete copy.") & "</pre>"
Response.End
End If
End If
success = http.HttpNoBody("GET","https://gmail.googleapis.com/gmail/v1/users/me/profile",resp)
If (resp.StatusCode = 0) Then
Response.Write "<pre>" & Server.HTMLEncode( "Gmail did not return an HTTP response.") & "</pre>"
Response.End
End If
If ((success <> 1) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Gmail HTTP " & resp.StatusCode) & "</pre>"
success = reply.Load(resp.BodyStr)
If (success = 1) Then
Response.Write "<pre>" & Server.HTMLEncode( reply.StringOf("error.message")) & "</pre>"
End If
Response.End
End If
success = reply.Load(resp.BodyStr)
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Expected a Gmail JSON response.") & "</pre>"
Response.End
End If
If ((reply.JsonTypeOf("emailAddress") <> 1) Or (reply.StringOfEquals("emailAddress","",1) = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Expected emailAddress in the response.") & "</pre>"
Response.End
End If
If ((reply.JsonTypeOf("historyId") <> 1) Or (reply.StringOfEquals("historyId","",1) = 1)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Expected historyId in the response.") & "</pre>"
Response.End
End If
mailbox = reply.StringOf("emailAddress")
baseline = reply.StringOf("historyId")
If (fileStatus = 1) Then
If (state.StringOfEquals("emailAddress",mailbox,0) <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Use a separate synchronization file for this mailbox.") & "</pre>"
Response.End
End If
End If
fullSync = fileStatus = 0
checkpoint = baseline
' A hashtable collects each changed ID once, even across multiple history records.
set ids = Server.CreateObject("Chilkat.Hashtable")
set baseUrl = Server.CreateObject("Chilkat.StringBuilder")
set url = Server.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 = Server.CreateObject("Chilkat.StringTable")
success = changeTypes.Append("messagesAdded")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( changeTypes.LastErrorText) & "</pre>"
Response.End
End If
success = changeTypes.Append("messagesDeleted")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( changeTypes.LastErrorText) & "</pre>"
Response.End
End If
success = changeTypes.Append("labelsAdded")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( changeTypes.LastErrorText) & "</pre>"
Response.End
End If
success = changeTypes.Append("labelsRemoved")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( changeTypes.LastErrorText) & "</pre>"
Response.End
End If
set record = Server.CreateObject("Chilkat.JsonObject")
set eventPath = Server.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
Response.Write "<pre>" & Server.HTMLEncode( "History checkpoint expired. Rebuilding the cache.") & "</pre>"
fullSync = 1
more = 0
Else
If (resp.StatusCode = 0) Then
Response.Write "<pre>" & Server.HTMLEncode( "Gmail did not return an HTTP response.") & "</pre>"
Response.End
End If
If ((success <> 1) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Gmail HTTP " & resp.StatusCode) & "</pre>"
success = reply.Load(resp.BodyStr)
If (success = 1) Then
Response.Write "<pre>" & Server.HTMLEncode( reply.StringOf("error.message")) & "</pre>"
End If
Response.End
End If
success = reply.Load(resp.BodyStr)
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Expected a Gmail JSON response.") & "</pre>"
Response.End
End If
h = 0
Do While (h < reply.SizeOfArray("history"))
reply.I = h
success = reply.ObjectOf2("history[i]",record)
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( reply.LastErrorText) & "</pre>"
Response.End
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
Response.Write "<pre>" & Server.HTMLEncode( ids.LastErrorText) & "</pre>"
Response.End
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
Response.Write "<pre>" & Server.HTMLEncode( "Expected historyId in the response.") & "</pre>"
Response.End
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
Response.Write "<pre>" & Server.HTMLEncode( state.LastErrorText) & "</pre>"
Response.End
End If
success = state.UpdateNewObject("messages")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( state.LastErrorText) & "</pre>"
Response.End
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
Response.Write "<pre>" & Server.HTMLEncode( "Gmail did not return an HTTP response.") & "</pre>"
Response.End
End If
If ((success <> 1) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Gmail HTTP " & resp.StatusCode) & "</pre>"
success = reply.Load(resp.BodyStr)
If (success = 1) Then
Response.Write "<pre>" & Server.HTMLEncode( reply.StringOf("error.message")) & "</pre>"
End If
Response.End
End If
success = reply.Load(resp.BodyStr)
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Expected a Gmail JSON response.") & "</pre>"
Response.End
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
Response.Write "<pre>" & Server.HTMLEncode( ids.LastErrorText) & "</pre>"
Response.End
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 = Server.CreateObject("Chilkat.JsonObject")
success = state.ObjectOf2("messages",messages)
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( state.LastErrorText) & "</pre>"
Response.End
End If
' Message refresh order is unimportant. GetKeys appends keys to this new table.
set messageIds = Server.CreateObject("Chilkat.StringTable")
success = ids.GetKeys(messageIds)
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( ids.LastErrorText) & "</pre>"
Response.End
End If
set cachedMessage = Server.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
Response.Write "<pre>" & Server.HTMLEncode( messages.LastErrorText) & "</pre>"
Response.End
End If
End If
Response.Write "<pre>" & Server.HTMLEncode( "Removed from cache: " & messageId) & "</pre>"
Else
If (resp.StatusCode = 0) Then
Response.Write "<pre>" & Server.HTMLEncode( "Gmail did not return an HTTP response.") & "</pre>"
Response.End
End If
If ((success <> 1) Or (resp.StatusCode < 200) Or (resp.StatusCode >= 300)) Then
Response.Write "<pre>" & Server.HTMLEncode( "Gmail HTTP " & resp.StatusCode) & "</pre>"
success = reply.Load(resp.BodyStr)
If (success = 1) Then
Response.Write "<pre>" & Server.HTMLEncode( reply.StringOf("error.message")) & "</pre>"
End If
Response.End
End If
success = reply.Load(resp.BodyStr)
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Expected a Gmail JSON response.") & "</pre>"
Response.End
End If
If (reply.StringOfEquals("id",messageId,1) <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Unexpected message ID in the response.") & "</pre>"
Response.End
End If
success = messages.UpdateNewObject(messageId)
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( messages.LastErrorText) & "</pre>"
Response.End
End If
success = messages.ObjectOf2(messageId,cachedMessage)
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( messages.LastErrorText) & "</pre>"
Response.End
End If
success = cachedMessage.Load(reply.Emit())
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( cachedMessage.LastErrorText) & "</pre>"
Response.End
End If
Response.Write "<pre>" & Server.HTMLEncode( "Cached message: " & messageId) & "</pre>"
End If
i = i + 1
Loop
success = state.UpdateString("historyId",checkpoint)
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( state.LastErrorText) & "</pre>"
Response.End
End If
' Prepare the complete replacement before moving the last committed file.
success = state.WriteFile("gmail-sync.json.new")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not write the replacement file.") & "</pre>"
Response.End
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
Response.Write "<pre>" & Server.HTMLEncode( "Could not rotate the previous backup.") & "</pre>"
Response.End
End If
End If
success = files.FileRename("gmail-sync.json","gmail-sync.json.previous")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not retain the previous complete file.") & "</pre>"
Response.End
End If
End If
success = files.FileRename("gmail-sync.json.new","gmail-sync.json")
If (success <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode( "Could not commit the replacement. The previous complete file is retained.") & "</pre>"
Response.End
End If
Response.Write "<pre>" & Server.HTMLEncode( "Synchronization committed. Cached messages: " & messages.Size) & "</pre>"
Response.Write "<pre>" & Server.HTMLEncode( "Saved history ID: " & checkpoint) & "</pre>"
%>
</body>
</html>