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 Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
var success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
final token = CkJsonObject();
success = true;
try {
token.loadFile('gmail-token.json');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not read gmail-token.json from the private working directory.');
return;
}
if ((token.jsonTypeOf('access_token') != 1) || (token.stringOfEquals('access_token', '', true))) {
print('An OAuth access token is required.');
return;
}
final http = CkHttp();
http.requireSslCertVerify = true;
http.authToken = token.stringOf('access_token');
final resp = CkHttpResponse();
final reply = CkJsonObject();
final files = CkFileAccess();
// Recover the previous complete file if a run stopped during replacement.
var fileStatus = files.fileExists3('gmail-sync.json');
if (fileStatus < 0) {
print('Could not inspect gmail-sync.json.');
return;
}
if (fileStatus == 0) {
final backupStatus = files.fileExists3('gmail-sync.json.previous');
if (backupStatus < 0) {
print('Could not inspect the backup file.');
return;
}
if (backupStatus == 1) {
success = true;
try {
files.fileRename('gmail-sync.json.previous', 'gmail-sync.json');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not restore the previous complete file.');
return;
}
fileStatus = 1;
}
}
final state = CkJsonObject();
if (fileStatus == 1) {
success = true;
try {
state.loadFile('gmail-sync.json');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not read the existing synchronization state.');
return;
}
if ((state.jsonTypeOf('historyId') != 1) || ((state.jsonTypeOf('messages') != 3) || (state.jsonTypeOf('emailAddress') != 1))) {
print('The synchronization state is incomplete. Restore its previous complete copy.');
return;
}
}
success = true;
try {
http.httpNoBody('GET', 'https://gmail.googleapis.com/gmail/v1/users/me/profile', resp);
} on ChilkatException {
success = false;
}
if (resp.statusCode == 0) {
print('Gmail did not return an HTTP response.');
return;
}
if ((!success) || ((resp.statusCode < 200) || (resp.statusCode >= 300))) {
print('Gmail HTTP ${resp.statusCode}');
success = true;
try {
reply.load(resp.bodyStr);
} on ChilkatException {
success = false;
}
if (success) {
print(reply.stringOf('error.message'));
}
return;
}
success = true;
try {
reply.load(resp.bodyStr);
} on ChilkatException {
success = false;
}
if (!success) {
print('Expected a Gmail JSON response.');
return;
}
if ((reply.jsonTypeOf('emailAddress') != 1) || (reply.stringOfEquals('emailAddress', '', true))) {
print('Expected emailAddress in the response.');
return;
}
if ((reply.jsonTypeOf('historyId') != 1) || (reply.stringOfEquals('historyId', '', true))) {
print('Expected historyId in the response.');
return;
}
final mailbox = reply.stringOf('emailAddress');
final baseline = reply.stringOf('historyId');
if (fileStatus == 1) {
if (!state.stringOfEquals('emailAddress', mailbox, false)) {
print('Use a separate synchronization file for this mailbox.');
return;
}
}
var fullSync = fileStatus == 0;
var checkpoint = baseline;
// A hashtable collects each changed ID once, even across multiple history records.
final ids = CkHashtable();
final baseUrl = CkStringBuilder();
final url = CkStringBuilder();
var pageToken = '';
var more = true;
if (!fullSync) {
baseUrl.setString('https://gmail.googleapis.com/gmail/v1/users/me/history?maxResults=500&startHistoryId=');
baseUrl.append(http.urlEncode(state.stringOf('historyId')));
final changeTypes = CkStringTable();
success = true;
try {
changeTypes.append('messagesAdded');
} on ChilkatException {
success = false;
}
if (!success) {
print(changeTypes.lastErrorText);
return;
}
success = true;
try {
changeTypes.append('messagesDeleted');
} on ChilkatException {
success = false;
}
if (!success) {
print(changeTypes.lastErrorText);
return;
}
success = true;
try {
changeTypes.append('labelsAdded');
} on ChilkatException {
success = false;
}
if (!success) {
print(changeTypes.lastErrorText);
return;
}
success = true;
try {
changeTypes.append('labelsRemoved');
} on ChilkatException {
success = false;
}
if (!success) {
print(changeTypes.lastErrorText);
return;
}
final record = CkJsonObject();
final eventPath = CkStringBuilder();
while (more) {
url.setString(baseUrl.getAsString());
url.append('&pageToken=');
url.append(http.urlEncode(pageToken));
success = true;
try {
http.httpNoBody('GET', url.getAsString(), resp);
} on ChilkatException {
success = false;
}
if (resp.statusCode == 404) {
print('History checkpoint expired. Rebuilding the cache.');
fullSync = true;
more = false;
} else {
if (resp.statusCode == 0) {
print('Gmail did not return an HTTP response.');
return;
}
if ((!success) || ((resp.statusCode < 200) || (resp.statusCode >= 300))) {
print('Gmail HTTP ${resp.statusCode}');
success = true;
try {
reply.load(resp.bodyStr);
} on ChilkatException {
success = false;
}
if (success) {
print(reply.stringOf('error.message'));
}
return;
}
success = true;
try {
reply.load(resp.bodyStr);
} on ChilkatException {
success = false;
}
if (!success) {
print('Expected a Gmail JSON response.');
return;
}
var h = 0;
while (h < reply.sizeOfArray('history')) {
reply.i = h;
success = true;
try {
reply.objectOf2('history[i]', record);
} on ChilkatException {
success = false;
}
if (!success) {
print(reply.lastErrorText);
return;
}
var t = 0;
while (t < changeTypes.count) {
var j = 0;
while (j < record.sizeOfArray(changeTypes.stringAt(t))) {
eventPath.setString(changeTypes.stringAt(t));
eventPath.append('[');
eventPath.appendInt(j);
eventPath.append('].message.id');
success = true;
try {
ids.addInt(record.stringOf(eventPath.getAsString()), 1);
} on ChilkatException {
success = false;
}
if (!success) {
print(ids.lastErrorText);
return;
}
j++;
}
t++;
}
h++;
}
pageToken = '';
if (reply.jsonTypeOf('nextPageToken') == 1) {
pageToken = reply.stringOf('nextPageToken');
}
more = pageToken != '';
if (!more) {
if ((reply.jsonTypeOf('historyId') != 1) || (reply.stringOfEquals('historyId', '', true))) {
print('Expected historyId in the response.');
return;
}
checkpoint = reply.stringOf('historyId');
}
}
}
}
if (fullSync) {
// Rebuild in memory. Any failure leaves the committed file available for a retry.
ids.clear();
state.clear();
success = true;
try {
state.updateString('emailAddress', mailbox);
} on ChilkatException {
success = false;
}
if (!success) {
print(state.lastErrorText);
return;
}
success = true;
try {
state.updateNewObject('messages');
} on ChilkatException {
success = false;
}
if (!success) {
print(state.lastErrorText);
return;
}
checkpoint = baseline;
pageToken = '';
more = true;
while (more) {
url.setString('https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=500&includeSpamTrash=true&pageToken=');
url.append(http.urlEncode(pageToken));
success = true;
try {
http.httpNoBody('GET', url.getAsString(), resp);
} on ChilkatException {
success = false;
}
if (resp.statusCode == 0) {
print('Gmail did not return an HTTP response.');
return;
}
if ((!success) || ((resp.statusCode < 200) || (resp.statusCode >= 300))) {
print('Gmail HTTP ${resp.statusCode}');
success = true;
try {
reply.load(resp.bodyStr);
} on ChilkatException {
success = false;
}
if (success) {
print(reply.stringOf('error.message'));
}
return;
}
success = true;
try {
reply.load(resp.bodyStr);
} on ChilkatException {
success = false;
}
if (!success) {
print('Expected a Gmail JSON response.');
return;
}
var m = 0;
while (m < reply.sizeOfArray('messages')) {
reply.i = m;
success = true;
try {
ids.addInt(reply.stringOf('messages[i].id'), 1);
} on ChilkatException {
success = false;
}
if (!success) {
print(ids.lastErrorText);
return;
}
m++;
}
pageToken = '';
if (reply.jsonTypeOf('nextPageToken') == 1) {
pageToken = reply.stringOf('nextPageToken');
}
more = pageToken != '';
}
}
final messages = CkJsonObject();
success = true;
try {
state.objectOf2('messages', messages);
} on ChilkatException {
success = false;
}
if (!success) {
print(state.lastErrorText);
return;
}
// Message refresh order is unimportant. GetKeys appends keys to this new table.
final messageIds = CkStringTable();
success = true;
try {
ids.getKeys(messageIds);
} on ChilkatException {
success = false;
}
if (!success) {
print(ids.lastErrorText);
return;
}
final cachedMessage = CkJsonObject();
var i = 0;
while (i < messageIds.count) {
final messageId = 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 = true;
try {
http.httpNoBody('GET', url.getAsString(), resp);
} on ChilkatException {
success = false;
}
if (resp.statusCode == 404) {
if (messages.hasMember(messageId)) {
success = true;
try {
messages.delete(messageId);
} on ChilkatException {
success = false;
}
if (!success) {
print(messages.lastErrorText);
return;
}
}
print('Removed from cache: $messageId');
} else {
if (resp.statusCode == 0) {
print('Gmail did not return an HTTP response.');
return;
}
if ((!success) || ((resp.statusCode < 200) || (resp.statusCode >= 300))) {
print('Gmail HTTP ${resp.statusCode}');
success = true;
try {
reply.load(resp.bodyStr);
} on ChilkatException {
success = false;
}
if (success) {
print(reply.stringOf('error.message'));
}
return;
}
success = true;
try {
reply.load(resp.bodyStr);
} on ChilkatException {
success = false;
}
if (!success) {
print('Expected a Gmail JSON response.');
return;
}
if (!reply.stringOfEquals('id', messageId, true)) {
print('Unexpected message ID in the response.');
return;
}
success = true;
try {
messages.updateNewObject(messageId);
} on ChilkatException {
success = false;
}
if (!success) {
print(messages.lastErrorText);
return;
}
success = true;
try {
messages.objectOf2(messageId, cachedMessage);
} on ChilkatException {
success = false;
}
if (!success) {
print(messages.lastErrorText);
return;
}
success = true;
try {
cachedMessage.load(reply.emit());
} on ChilkatException {
success = false;
}
if (!success) {
print(cachedMessage.lastErrorText);
return;
}
print('Cached message: $messageId');
}
i++;
}
success = true;
try {
state.updateString('historyId', checkpoint);
} on ChilkatException {
success = false;
}
if (!success) {
print(state.lastErrorText);
return;
}
// Prepare the complete replacement before moving the last committed file.
success = true;
try {
state.writeFile('gmail-sync.json.new');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not write the replacement file.');
return;
}
if (files.fileExists('gmail-sync.json')) {
if (files.fileExists('gmail-sync.json.previous')) {
success = true;
try {
files.fileDelete('gmail-sync.json.previous');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not rotate the previous backup.');
return;
}
}
success = true;
try {
files.fileRename('gmail-sync.json', 'gmail-sync.json.previous');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not retain the previous complete file.');
return;
}
}
success = true;
try {
files.fileRename('gmail-sync.json.new', 'gmail-sync.json');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not commit the replacement. The previous complete file is retained.');
return;
}
print('Synchronization committed. Cached messages: ${messages.size}');
print('Saved history ID: $checkpoint');
}