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 Swift Downloads
func chilkatTest() {
var success: Bool = false
// Assumes Chilkat is unlocked. See Global Unlock Sample.
let token = CkoJsonObject()!
success = token.loadFile(path: "gmail-token.json")
if success != true {
print("Could not read gmail-token.json from the private working directory.")
return
}
if (token.jsonType(of: "access_token").intValue != 1) || (token.string(ofEquals: "access_token", value: "", caseSensitive: true) == true) {
print("An OAuth access token is required.")
return
}
let http = CkoHttp()!
http.requireSslCertVerify = true
http.authToken = token.string(of: "access_token")
let resp = CkoHttpResponse()!
let reply = CkoJsonObject()!
let files = CkoFileAccess()!
// Recover the previous complete file if a run stopped during replacement.
var fileStatus: Int = files.fileExists3(path: "gmail-sync.json").intValue
if fileStatus < 0 {
print("Could not inspect gmail-sync.json.")
return
}
if fileStatus == 0 {
var backupStatus: Int = files.fileExists3(path: "gmail-sync.json.previous").intValue
if backupStatus < 0 {
print("Could not inspect the backup file.")
return
}
if backupStatus == 1 {
success = files.fileRename(existingPath: "gmail-sync.json.previous", newPath: "gmail-sync.json")
if success != true {
print("Could not restore the previous complete file.")
return
}
fileStatus = 1
}
}
let state = CkoJsonObject()!
if fileStatus == 1 {
success = state.loadFile(path: "gmail-sync.json")
if success != true {
print("Could not read the existing synchronization state.")
return
}
if (state.jsonType(of: "historyId").intValue != 1) || (state.jsonType(of: "messages").intValue != 3) || (state.jsonType(of: "emailAddress").intValue != 1) {
print("The synchronization state is incomplete. Restore its previous complete copy.")
return
}
}
success = http.httpNoBody(verb: "GET", url: "https://gmail.googleapis.com/gmail/v1/users/me/profile", response: resp)
if resp.statusCode.intValue == 0 {
print("Gmail did not return an HTTP response.")
return
}
if (success != true) || (resp.statusCode.intValue < 200) || (resp.statusCode.intValue >= 300) {
print("Gmail HTTP \(resp.statusCode.intValue)")
success = reply.load(json: resp.bodyStr)
if success == true {
print("\(reply.string(of: "error.message")!)")
}
return
}
success = reply.load(json: resp.bodyStr)
if success != true {
print("Expected a Gmail JSON response.")
return
}
if (reply.jsonType(of: "emailAddress").intValue != 1) || (reply.string(ofEquals: "emailAddress", value: "", caseSensitive: true) == true) {
print("Expected emailAddress in the response.")
return
}
if (reply.jsonType(of: "historyId").intValue != 1) || (reply.string(ofEquals: "historyId", value: "", caseSensitive: true) == true) {
print("Expected historyId in the response.")
return
}
var mailbox: String? = reply.string(of: "emailAddress")
var baseline: String? = reply.string(of: "historyId")
if fileStatus == 1 {
if state.string(ofEquals: "emailAddress", value: mailbox, caseSensitive: false) != true {
print("Use a separate synchronization file for this mailbox.")
return
}
}
var fullSync: Bool = fileStatus == 0
var checkpoint: String? = baseline
// A hashtable collects each changed ID once, even across multiple history records.
let ids = CkoHashtable()!
let baseUrl = CkoStringBuilder()!
let url = CkoStringBuilder()!
var pageToken: String? = ""
var more: Bool = true
if fullSync != true {
baseUrl.setString(value: "https://gmail.googleapis.com/gmail/v1/users/me/history?maxResults=500&startHistoryId=")
baseUrl.append(value: http.urlEncode(str: state.string(of: "historyId")))
let changeTypes = CkoStringTable()!
success = changeTypes.append(value: "messagesAdded")
if success != true {
print("\(changeTypes.lastErrorText!)")
return
}
success = changeTypes.append(value: "messagesDeleted")
if success != true {
print("\(changeTypes.lastErrorText!)")
return
}
success = changeTypes.append(value: "labelsAdded")
if success != true {
print("\(changeTypes.lastErrorText!)")
return
}
success = changeTypes.append(value: "labelsRemoved")
if success != true {
print("\(changeTypes.lastErrorText!)")
return
}
let record = CkoJsonObject()!
let eventPath = CkoStringBuilder()!
while (more == true) {
url.setString(value: baseUrl.getAsString())
url.append(value: "&pageToken=")
url.append(value: http.urlEncode(str: pageToken))
success = http.httpNoBody(verb: "GET", url: url.getAsString(), response: resp)
if resp.statusCode.intValue == 404 {
print("History checkpoint expired. Rebuilding the cache.")
fullSync = true
more = false
}
else {
if resp.statusCode.intValue == 0 {
print("Gmail did not return an HTTP response.")
return
}
if (success != true) || (resp.statusCode.intValue < 200) || (resp.statusCode.intValue >= 300) {
print("Gmail HTTP \(resp.statusCode.intValue)")
success = reply.load(json: resp.bodyStr)
if success == true {
print("\(reply.string(of: "error.message")!)")
}
return
}
success = reply.load(json: resp.bodyStr)
if success != true {
print("Expected a Gmail JSON response.")
return
}
var h: Int = 0
while (h < reply.size(ofArray: "history").intValue) {
reply.i = h
success = reply.objectOf2(jsonPath: "history[i]", jsonObj: record)
if success != true {
print("\(reply.lastErrorText!)")
return
}
var t: Int = 0
while (t < changeTypes.count.intValue) {
var j: Int = 0
while (j < record.size(ofArray: changeTypes.string(at: t)).intValue) {
eventPath.setString(value: changeTypes.string(at: t))
eventPath.append(value: "[")
eventPath.appendInt(value: j)
eventPath.append(value: "].message.id")
success = ids.addInt(key: record.string(of: eventPath.getAsString()), value: 1)
if success != true {
print("\(ids.lastErrorText!)")
return
}
j = j + 1
}
t = t + 1
}
h = h + 1
}
pageToken = ""
if reply.jsonType(of: "nextPageToken").intValue == 1 {
pageToken = reply.string(of: "nextPageToken")
}
more = pageToken != ""
if more != true {
if (reply.jsonType(of: "historyId").intValue != 1) || (reply.string(ofEquals: "historyId", value: "", caseSensitive: true) == true) {
print("Expected historyId in the response.")
return
}
checkpoint = reply.string(of: "historyId")
}
}
}
}
if fullSync == true {
// Rebuild in memory. Any failure leaves the committed file available for a retry.
ids.clear()
state.clear()
success = state.updateString(jsonPath: "emailAddress", value: mailbox)
if success != true {
print("\(state.lastErrorText!)")
return
}
success = state.updateNew(jsonPath: "messages")
if success != true {
print("\(state.lastErrorText!)")
return
}
checkpoint = baseline
pageToken = ""
more = true
while (more == true) {
url.setString(value: "https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=500&includeSpamTrash=true&pageToken=")
url.append(value: http.urlEncode(str: pageToken))
success = http.httpNoBody(verb: "GET", url: url.getAsString(), response: resp)
if resp.statusCode.intValue == 0 {
print("Gmail did not return an HTTP response.")
return
}
if (success != true) || (resp.statusCode.intValue < 200) || (resp.statusCode.intValue >= 300) {
print("Gmail HTTP \(resp.statusCode.intValue)")
success = reply.load(json: resp.bodyStr)
if success == true {
print("\(reply.string(of: "error.message")!)")
}
return
}
success = reply.load(json: resp.bodyStr)
if success != true {
print("Expected a Gmail JSON response.")
return
}
var m: Int = 0
while (m < reply.size(ofArray: "messages").intValue) {
reply.i = m
success = ids.addInt(key: reply.string(of: "messages[i].id"), value: 1)
if success != true {
print("\(ids.lastErrorText!)")
return
}
m = m + 1
}
pageToken = ""
if reply.jsonType(of: "nextPageToken").intValue == 1 {
pageToken = reply.string(of: "nextPageToken")
}
more = pageToken != ""
}
}
let messages = CkoJsonObject()!
success = state.objectOf2(jsonPath: "messages", jsonObj: messages)
if success != true {
print("\(state.lastErrorText!)")
return
}
// Message refresh order is unimportant. GetKeys appends keys to this new table.
let messageIds = CkoStringTable()!
success = ids.getKeys(strTable: messageIds)
if success != true {
print("\(ids.lastErrorText!)")
return
}
let cachedMessage = CkoJsonObject()!
var i: Int = 0
while (i < messageIds.count.intValue) {
var messageId: String? = messageIds.string(at: i)
url.setString(value: "https://gmail.googleapis.com/gmail/v1/users/me/messages/")
url.append(value: http.urlEncode(str: messageId))
url.append(value: "?format=minimal&fields=id,threadId,labelIds")
success = http.httpNoBody(verb: "GET", url: url.getAsString(), response: resp)
if resp.statusCode.intValue == 404 {
if messages.hasMember(jsonPath: messageId) == true {
success = messages.delete(name: messageId)
if success != true {
print("\(messages.lastErrorText!)")
return
}
}
print("Removed from cache: \(messageId!)")
}
else {
if resp.statusCode.intValue == 0 {
print("Gmail did not return an HTTP response.")
return
}
if (success != true) || (resp.statusCode.intValue < 200) || (resp.statusCode.intValue >= 300) {
print("Gmail HTTP \(resp.statusCode.intValue)")
success = reply.load(json: resp.bodyStr)
if success == true {
print("\(reply.string(of: "error.message")!)")
}
return
}
success = reply.load(json: resp.bodyStr)
if success != true {
print("Expected a Gmail JSON response.")
return
}
if reply.string(ofEquals: "id", value: messageId, caseSensitive: true) != true {
print("Unexpected message ID in the response.")
return
}
success = messages.updateNew(jsonPath: messageId)
if success != true {
print("\(messages.lastErrorText!)")
return
}
success = messages.objectOf2(jsonPath: messageId, jsonObj: cachedMessage)
if success != true {
print("\(messages.lastErrorText!)")
return
}
success = cachedMessage.load(json: reply.emit())
if success != true {
print("\(cachedMessage.lastErrorText!)")
return
}
print("Cached message: \(messageId!)")
}
i = i + 1
}
success = state.updateString(jsonPath: "historyId", value: checkpoint)
if success != true {
print("\(state.lastErrorText!)")
return
}
// Prepare the complete replacement before moving the last committed file.
success = state.writeFile(path: "gmail-sync.json.new")
if success != true {
print("Could not write the replacement file.")
return
}
if files.fileExists(path: "gmail-sync.json") == true {
if files.fileExists(path: "gmail-sync.json.previous") == true {
success = files.fileDelete(path: "gmail-sync.json.previous")
if success != true {
print("Could not rotate the previous backup.")
return
}
}
success = files.fileRename(existingPath: "gmail-sync.json", newPath: "gmail-sync.json.previous")
if success != true {
print("Could not retain the previous complete file.")
return
}
}
success = files.fileRename(existingPath: "gmail-sync.json.new", newPath: "gmail-sync.json")
if success != true {
print("Could not commit the replacement. The previous complete file is retained.")
return
}
print("Synchronization committed. Cached messages: \(messages.size.intValue)")
print("Saved history ID: \(checkpoint!)")
}