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 Lazarus Pascal Downloads
program ChilkatDemo;
// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
SysUtils,
CkDllLoader,
Chilkat.StringTable,
Chilkat.Http,
Chilkat.HttpResponse,
Chilkat.FileAccess,
Chilkat.JsonObject,
Chilkat.StringBuilder,
Chilkat.StringArray;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
token: TJsonObject;
http: THttp;
resp: THttpResponse;
reply: TJsonObject;
files: TFileAccess;
fileStatus: Integer;
backupStatus: Integer;
state: TJsonObject;
mailbox: string;
baseline: string;
fullSync: Boolean;
checkpoint: string;
ids: TStringArray;
baseUrl: TStringBuilder;
url: TStringBuilder;
pageToken: string;
more: Boolean;
changeTypes: TStringTable;
record: TJsonObject;
eventPath: TStringBuilder;
h: Integer;
t: Integer;
j: Integer;
m: Integer;
messages: TJsonObject;
cachedMessage: TJsonObject;
i: Integer;
messageId: string;
begin
success := False;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
token := TJsonObject.Create;
success := token.LoadFile('gmail-token.json');
if (success <> True) then
begin
WriteLn('Could not read gmail-token.json from the private working directory.');
Exit;
end;
if ((token.JsonTypeOf('access_token') <> 1) or (token.StringOfEquals('access_token','',True) = True)) then
begin
WriteLn('An OAuth access token is required.');
Exit;
end;
http := THttp.Create;
http.RequireSslCertVerify := True;
http.AuthToken := token.StringOf('access_token');
resp := THttpResponse.Create;
reply := TJsonObject.Create;
files := TFileAccess.Create;
// Recover the previous complete file if a run stopped during replacement.
fileStatus := files.FileExists3('gmail-sync.json');
if (fileStatus < 0) then
begin
WriteLn('Could not inspect gmail-sync.json.');
Exit;
end;
if (fileStatus = 0) then
begin
backupStatus := files.FileExists3('gmail-sync.json.previous');
if (backupStatus < 0) then
begin
WriteLn('Could not inspect the backup file.');
Exit;
end;
if (backupStatus = 1) then
begin
success := files.FileRename('gmail-sync.json.previous','gmail-sync.json');
if (success <> True) then
begin
WriteLn('Could not restore the previous complete file.');
Exit;
end;
fileStatus := 1;
end;
end;
state := TJsonObject.Create;
if (fileStatus = 1) then
begin
success := state.LoadFile('gmail-sync.json');
if (success <> True) then
begin
WriteLn('Could not read the existing synchronization state.');
Exit;
end;
if ((state.JsonTypeOf('historyId') <> 1) or (state.JsonTypeOf('messages') <> 3) or (state.JsonTypeOf('emailAddress') <> 1)) then
begin
WriteLn('The synchronization state is incomplete. Restore its previous complete copy.');
Exit;
end;
end;
success := http.HttpNoBody('GET','https://gmail.googleapis.com/gmail/v1/users/me/profile',resp);
if (resp.StatusCode = 0) then
begin
WriteLn('Gmail did not return an HTTP response.');
Exit;
end;
if ((success <> True) or (resp.StatusCode < 200) or (resp.StatusCode >= 300)) then
begin
WriteLn('Gmail HTTP ' + resp.StatusCode);
success := reply.Load(resp.BodyStr);
if (success = True) then
begin
WriteLn(reply.StringOf('error.message'));
end;
Exit;
end;
success := reply.Load(resp.BodyStr);
if (success <> True) then
begin
WriteLn('Expected a Gmail JSON response.');
Exit;
end;
if ((reply.JsonTypeOf('emailAddress') <> 1) or (reply.StringOfEquals('emailAddress','',True) = True)) then
begin
WriteLn('Expected emailAddress in the response.');
Exit;
end;
if ((reply.JsonTypeOf('historyId') <> 1) or (reply.StringOfEquals('historyId','',True) = True)) then
begin
WriteLn('Expected historyId in the response.');
Exit;
end;
mailbox := reply.StringOf('emailAddress');
baseline := reply.StringOf('historyId');
if (fileStatus = 1) then
begin
if (state.StringOfEquals('emailAddress',mailbox,False) <> True) then
begin
WriteLn('Use a separate synchronization file for this mailbox.');
Exit;
end;
end;
fullSync := fileStatus = 0;
checkpoint := baseline;
ids := TStringArray.Create;
ids.Unique := True;
baseUrl := TStringBuilder.Create;
url := TStringBuilder.Create;
pageToken := '';
more := True;
if (fullSync <> True) then
begin
baseUrl.SetString('https://gmail.googleapis.com/gmail/v1/users/me/history?maxResults=500&startHistoryId=');
baseUrl.Append(http.UrlEncode(state.StringOf('historyId')));
changeTypes := TStringTable.Create;
success := changeTypes.Append('messagesAdded');
if (success <> True) then
begin
WriteLn(changeTypes.LastErrorText);
Exit;
end;
success := changeTypes.Append('messagesDeleted');
if (success <> True) then
begin
WriteLn(changeTypes.LastErrorText);
Exit;
end;
success := changeTypes.Append('labelsAdded');
if (success <> True) then
begin
WriteLn(changeTypes.LastErrorText);
Exit;
end;
success := changeTypes.Append('labelsRemoved');
if (success <> True) then
begin
WriteLn(changeTypes.LastErrorText);
Exit;
end;
record := TJsonObject.Create;
eventPath := TStringBuilder.Create;
while (more = True) do
begin
url.SetString(baseUrl.GetAsString());
url.Append('&pageToken=');
url.Append(http.UrlEncode(pageToken));
success := http.HttpNoBody('GET',url.GetAsString(),resp);
if (resp.StatusCode = 404) then
begin
WriteLn('History checkpoint expired. Rebuilding the cache.');
fullSync := True;
more := False;
end
else
begin
if (resp.StatusCode = 0) then
begin
WriteLn('Gmail did not return an HTTP response.');
Exit;
end;
if ((success <> True) or (resp.StatusCode < 200) or (resp.StatusCode >= 300)) then
begin
WriteLn('Gmail HTTP ' + resp.StatusCode);
success := reply.Load(resp.BodyStr);
if (success = True) then
begin
WriteLn(reply.StringOf('error.message'));
end;
Exit;
end;
success := reply.Load(resp.BodyStr);
if (success <> True) then
begin
WriteLn('Expected a Gmail JSON response.');
Exit;
end;
h := 0;
while (h < reply.SizeOfArray('history')) do
begin
reply.I := h;
success := reply.ObjectOf2('history[i]',record);
if (success <> True) then
begin
WriteLn(reply.LastErrorText);
Exit;
end;
t := 0;
while (t < changeTypes.Count) do
begin
j := 0;
while (j < record.SizeOfArray(changeTypes.StringAt(t))) do
begin
eventPath.SetString(changeTypes.StringAt(t));
eventPath.Append('[');
eventPath.AppendInt(j);
eventPath.Append('].message.id');
success := ids.Append(record.StringOf(eventPath.GetAsString()));
if (success <> True) then
begin
WriteLn(ids.LastErrorText);
Exit;
end;
j := j + 1;
end;
t := t + 1;
end;
h := h + 1;
end;
pageToken := '';
if (reply.JsonTypeOf('nextPageToken') = 1) then
begin
pageToken := reply.StringOf('nextPageToken');
end;
more := pageToken <> '';
if (more <> True) then
begin
if ((reply.JsonTypeOf('historyId') <> 1) or (reply.StringOfEquals('historyId','',True) = True)) then
begin
WriteLn('Expected historyId in the response.');
Exit;
end;
checkpoint := reply.StringOf('historyId');
end;
end;
end;
end;
if (fullSync = True) then
begin
// 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
begin
WriteLn(state.LastErrorText);
Exit;
end;
success := state.UpdateNewObject('messages');
if (success <> True) then
begin
WriteLn(state.LastErrorText);
Exit;
end;
checkpoint := baseline;
pageToken := '';
more := True;
while (more = True) do
begin
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
begin
WriteLn('Gmail did not return an HTTP response.');
Exit;
end;
if ((success <> True) or (resp.StatusCode < 200) or (resp.StatusCode >= 300)) then
begin
WriteLn('Gmail HTTP ' + resp.StatusCode);
success := reply.Load(resp.BodyStr);
if (success = True) then
begin
WriteLn(reply.StringOf('error.message'));
end;
Exit;
end;
success := reply.Load(resp.BodyStr);
if (success <> True) then
begin
WriteLn('Expected a Gmail JSON response.');
Exit;
end;
m := 0;
while (m < reply.SizeOfArray('messages')) do
begin
reply.I := m;
success := ids.Append(reply.StringOf('messages[i].id'));
if (success <> True) then
begin
WriteLn(ids.LastErrorText);
Exit;
end;
m := m + 1;
end;
pageToken := '';
if (reply.JsonTypeOf('nextPageToken') = 1) then
begin
pageToken := reply.StringOf('nextPageToken');
end;
more := pageToken <> '';
end;
end;
messages := TJsonObject.Create;
success := state.ObjectOf2('messages',messages);
if (success <> True) then
begin
WriteLn(state.LastErrorText);
Exit;
end;
cachedMessage := TJsonObject.Create;
i := 0;
while (i < ids.Count) do
begin
messageId := ids.GetString(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
begin
if (messages.HasMember(messageId) = True) then
begin
success := messages.Delete(messageId);
if (success <> True) then
begin
WriteLn(messages.LastErrorText);
Exit;
end;
end;
WriteLn('Removed from cache: ' + messageId);
end
else
begin
if (resp.StatusCode = 0) then
begin
WriteLn('Gmail did not return an HTTP response.');
Exit;
end;
if ((success <> True) or (resp.StatusCode < 200) or (resp.StatusCode >= 300)) then
begin
WriteLn('Gmail HTTP ' + resp.StatusCode);
success := reply.Load(resp.BodyStr);
if (success = True) then
begin
WriteLn(reply.StringOf('error.message'));
end;
Exit;
end;
success := reply.Load(resp.BodyStr);
if (success <> True) then
begin
WriteLn('Expected a Gmail JSON response.');
Exit;
end;
if (reply.StringOfEquals('id',messageId,True) <> True) then
begin
WriteLn('Unexpected message ID in the response.');
Exit;
end;
success := messages.UpdateNewObject(messageId);
if (success <> True) then
begin
WriteLn(messages.LastErrorText);
Exit;
end;
success := messages.ObjectOf2(messageId,cachedMessage);
if (success <> True) then
begin
WriteLn(messages.LastErrorText);
Exit;
end;
success := cachedMessage.Load(reply.Emit());
if (success <> True) then
begin
WriteLn(cachedMessage.LastErrorText);
Exit;
end;
WriteLn('Cached message: ' + messageId);
end;
i := i + 1;
end;
success := state.UpdateString('historyId',checkpoint);
if (success <> True) then
begin
WriteLn(state.LastErrorText);
Exit;
end;
// Prepare the complete replacement before moving the last committed file.
success := state.WriteFile('gmail-sync.json.new');
if (success <> True) then
begin
WriteLn('Could not write the replacement file.');
Exit;
end;
if (files.FileExists('gmail-sync.json') = True) then
begin
if (files.FileExists('gmail-sync.json.previous') = True) then
begin
success := files.FileDelete('gmail-sync.json.previous');
if (success <> True) then
begin
WriteLn('Could not rotate the previous backup.');
Exit;
end;
end;
success := files.FileRename('gmail-sync.json','gmail-sync.json.previous');
if (success <> True) then
begin
WriteLn('Could not retain the previous complete file.');
Exit;
end;
end;
success := files.FileRename('gmail-sync.json.new','gmail-sync.json');
if (success <> True) then
begin
WriteLn('Could not commit the replacement. The previous complete file is retained.');
Exit;
end;
WriteLn('Synchronization committed. Cached messages: ' + messages.Size);
WriteLn('Saved history ID: ' + checkpoint);
token.Free;
http.Free;
resp.Free;
reply.Free;
files.Free;
state.Free;
ids.Free;
baseUrl.Free;
url.Free;
changeTypes.Free;
record.Free;
eventPath.Free;
messages.Free;
cachedMessage.Free;
end;
// ---------------------------------------------------------------------------
begin
try
RunDemo;
except
on E: Exception do
WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
end;
WriteLn;
{$IFDEF MSWINDOWS}
WriteLn('Press Enter to exit...');
ReadLn;
{$ENDIF}
end.