Sample code for 30+ languages & platforms
Delphi DLL Requires Chilkat v11.0.0+

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.

Google documentation

Chilkat Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
token: HCkJsonObject;
http: HCkHttp;
resp: HCkHttpResponse;
reply: HCkJsonObject;
files: HCkFileAccess;
fileStatus: Integer;
backupStatus: Integer;
state: HCkJsonObject;
mailbox: PWideChar;
baseline: PWideChar;
fullSync: Boolean;
checkpoint: PWideChar;
ids: HCkHashtable;
baseUrl: HCkStringBuilder;
url: HCkStringBuilder;
pageToken: PWideChar;
more: Boolean;
changeTypes: HCkStringTable;
record: HCkJsonObject;
eventPath: HCkStringBuilder;
h: Integer;
t: Integer;
j: Integer;
m: Integer;
messages: HCkJsonObject;
messageIds: HCkStringTable;
cachedMessage: HCkJsonObject;
i: Integer;
messageId: PWideChar;

begin
success := False;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.

token := CkJsonObject_Create();
success := CkJsonObject_LoadFile(token,'gmail-token.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not read gmail-token.json from the private working directory.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(token,'access_token') <> 1) or (CkJsonObject_StringOfEquals(token,'access_token','',True) = True)) then
  begin
    Memo1.Lines.Add('An OAuth access token is required.');
    Exit;
  end;
http := CkHttp_Create();
CkHttp_putRequireSslCertVerify(http,True);
CkHttp_putAuthToken(http,CkJsonObject__stringOf(token,'access_token'));
resp := CkHttpResponse_Create();
reply := CkJsonObject_Create();
files := CkFileAccess_Create();
//  Recover the previous complete file if a run stopped during replacement.
fileStatus := CkFileAccess_FileExists3(files,'gmail-sync.json');
if (fileStatus < 0) then
  begin
    Memo1.Lines.Add('Could not inspect gmail-sync.json.');
    Exit;
  end;
if (fileStatus = 0) then
  begin
    backupStatus := CkFileAccess_FileExists3(files,'gmail-sync.json.previous');
    if (backupStatus < 0) then
      begin
        Memo1.Lines.Add('Could not inspect the backup file.');
        Exit;
      end;
    if (backupStatus = 1) then
      begin
        success := CkFileAccess_FileRename(files,'gmail-sync.json.previous','gmail-sync.json');
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not restore the previous complete file.');
            Exit;
          end;
        fileStatus := 1;
      end;
  end;
state := CkJsonObject_Create();
if (fileStatus = 1) then
  begin
    success := CkJsonObject_LoadFile(state,'gmail-sync.json');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not read the existing synchronization state.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(state,'historyId') <> 1) or (CkJsonObject_JsonTypeOf(state,'messages') <> 3) or (CkJsonObject_JsonTypeOf(state,'emailAddress') <> 1)) then
      begin
        Memo1.Lines.Add('The synchronization state is incomplete. Restore its previous complete copy.');
        Exit;
      end;
  end;
success := CkHttp_HttpNoBody(http,'GET','https://gmail.googleapis.com/gmail/v1/users/me/profile',resp);
if (CkHttpResponse_getStatusCode(resp) = 0) then
  begin
    Memo1.Lines.Add('Gmail did not return an HTTP response.');
    Exit;
  end;
if ((success <> True) or (CkHttpResponse_getStatusCode(resp) < 200) or (CkHttpResponse_getStatusCode(resp) >= 300)) then
  begin
    Memo1.Lines.Add('Gmail HTTP ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
    success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
    if (success = True) then
      begin
        Memo1.Lines.Add(CkJsonObject__stringOf(reply,'error.message'));
      end;
    Exit;
  end;
success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
if (success <> True) then
  begin
    Memo1.Lines.Add('Expected a Gmail JSON response.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(reply,'emailAddress') <> 1) or (CkJsonObject_StringOfEquals(reply,'emailAddress','',True) = True)) then
  begin
    Memo1.Lines.Add('Expected emailAddress in the response.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(reply,'historyId') <> 1) or (CkJsonObject_StringOfEquals(reply,'historyId','',True) = True)) then
  begin
    Memo1.Lines.Add('Expected historyId in the response.');
    Exit;
  end;
mailbox := CkJsonObject__stringOf(reply,'emailAddress');
baseline := CkJsonObject__stringOf(reply,'historyId');
if (fileStatus = 1) then
  begin
    if (CkJsonObject_StringOfEquals(state,'emailAddress',mailbox,False) <> True) then
      begin
        Memo1.Lines.Add('Use a separate synchronization file for this mailbox.');
        Exit;
      end;
  end;
fullSync := fileStatus = 0;
checkpoint := baseline;
//  A hashtable collects each changed ID once, even across multiple history records.
ids := CkHashtable_Create();
baseUrl := CkStringBuilder_Create();
url := CkStringBuilder_Create();
pageToken := '';
more := True;

if (fullSync <> True) then
  begin
    CkStringBuilder_SetString(baseUrl,'https://gmail.googleapis.com/gmail/v1/users/me/history?maxResults=500&startHistoryId=');
    CkStringBuilder_Append(baseUrl,CkHttp__urlEncode(http,CkJsonObject__stringOf(state,'historyId')));
    changeTypes := CkStringTable_Create();
    success := CkStringTable_Append(changeTypes,'messagesAdded');
    if (success <> True) then
      begin
        Memo1.Lines.Add(CkStringTable__lastErrorText(changeTypes));
        Exit;
      end;
    success := CkStringTable_Append(changeTypes,'messagesDeleted');
    if (success <> True) then
      begin
        Memo1.Lines.Add(CkStringTable__lastErrorText(changeTypes));
        Exit;
      end;
    success := CkStringTable_Append(changeTypes,'labelsAdded');
    if (success <> True) then
      begin
        Memo1.Lines.Add(CkStringTable__lastErrorText(changeTypes));
        Exit;
      end;
    success := CkStringTable_Append(changeTypes,'labelsRemoved');
    if (success <> True) then
      begin
        Memo1.Lines.Add(CkStringTable__lastErrorText(changeTypes));
        Exit;
      end;
    record := CkJsonObject_Create();
    eventPath := CkStringBuilder_Create();
    while (more = True) do
      begin
        CkStringBuilder_SetString(url,CkStringBuilder__getAsString(baseUrl));
        CkStringBuilder_Append(url,'&pageToken=');
        CkStringBuilder_Append(url,CkHttp__urlEncode(http,pageToken));
        success := CkHttp_HttpNoBody(http,'GET',CkStringBuilder__getAsString(url),resp);
        if (CkHttpResponse_getStatusCode(resp) = 404) then
          begin
            Memo1.Lines.Add('History checkpoint expired. Rebuilding the cache.');
            fullSync := True;
            more := False;
          end
        else
          begin
            if (CkHttpResponse_getStatusCode(resp) = 0) then
              begin
                Memo1.Lines.Add('Gmail did not return an HTTP response.');
                Exit;
              end;
            if ((success <> True) or (CkHttpResponse_getStatusCode(resp) < 200) or (CkHttpResponse_getStatusCode(resp) >= 300)) then
              begin
                Memo1.Lines.Add('Gmail HTTP ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
                success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
                if (success = True) then
                  begin
                    Memo1.Lines.Add(CkJsonObject__stringOf(reply,'error.message'));
                  end;
                Exit;
              end;
            success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
            if (success <> True) then
              begin
                Memo1.Lines.Add('Expected a Gmail JSON response.');
                Exit;
              end;
            h := 0;
            while (h < CkJsonObject_SizeOfArray(reply,'history')) do
              begin
                CkJsonObject_putI(reply,h);
                success := CkJsonObject_ObjectOf2(reply,'history[i]',record);
                if (success <> True) then
                  begin
                    Memo1.Lines.Add(CkJsonObject__lastErrorText(reply));
                    Exit;
                  end;
                t := 0;
                while (t < CkStringTable_getCount(changeTypes)) do
                  begin
                    j := 0;
                    while (j < CkJsonObject_SizeOfArray(record,CkStringTable__stringAt(changeTypes,t))) do
                      begin
                        CkStringBuilder_SetString(eventPath,CkStringTable__stringAt(changeTypes,t));
                        CkStringBuilder_Append(eventPath,'[');
                        CkStringBuilder_AppendInt(eventPath,j);
                        CkStringBuilder_Append(eventPath,'].message.id');
                        success := CkHashtable_AddInt(ids,CkJsonObject__stringOf(record,CkStringBuilder__getAsString(eventPath)),1);
                        if (success <> True) then
                          begin
                            Memo1.Lines.Add(CkHashtable__lastErrorText(ids));
                            Exit;
                          end;
                        j := j + 1;
                      end;

                    t := t + 1;
                  end;

                h := h + 1;
              end;

            pageToken := '';
            if (CkJsonObject_JsonTypeOf(reply,'nextPageToken') = 1) then
              begin
                pageToken := CkJsonObject__stringOf(reply,'nextPageToken');
              end;
            more := pageToken <> '';
            if (more <> True) then
              begin
                if ((CkJsonObject_JsonTypeOf(reply,'historyId') <> 1) or (CkJsonObject_StringOfEquals(reply,'historyId','',True) = True)) then
                  begin
                    Memo1.Lines.Add('Expected historyId in the response.');
                    Exit;
                  end;
                checkpoint := CkJsonObject__stringOf(reply,'historyId');
              end;
          end;
      end;

  end;

if (fullSync = True) then
  begin
    //  Rebuild in memory. Any failure leaves the committed file available for a retry.
    CkHashtable_Clear(ids);
    CkJsonObject_Clear(state);
    success := CkJsonObject_UpdateString(state,'emailAddress',mailbox);
    if (success <> True) then
      begin
        Memo1.Lines.Add(CkJsonObject__lastErrorText(state));
        Exit;
      end;
    success := CkJsonObject_UpdateNewObject(state,'messages');
    if (success <> True) then
      begin
        Memo1.Lines.Add(CkJsonObject__lastErrorText(state));
        Exit;
      end;
    checkpoint := baseline;
    pageToken := '';
    more := True;
    while (more = True) do
      begin
        CkStringBuilder_SetString(url,'https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=500&includeSpamTrash=true&pageToken=');
        CkStringBuilder_Append(url,CkHttp__urlEncode(http,pageToken));
        success := CkHttp_HttpNoBody(http,'GET',CkStringBuilder__getAsString(url),resp);
        if (CkHttpResponse_getStatusCode(resp) = 0) then
          begin
            Memo1.Lines.Add('Gmail did not return an HTTP response.');
            Exit;
          end;
        if ((success <> True) or (CkHttpResponse_getStatusCode(resp) < 200) or (CkHttpResponse_getStatusCode(resp) >= 300)) then
          begin
            Memo1.Lines.Add('Gmail HTTP ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
            success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
            if (success = True) then
              begin
                Memo1.Lines.Add(CkJsonObject__stringOf(reply,'error.message'));
              end;
            Exit;
          end;
        success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
        if (success <> True) then
          begin
            Memo1.Lines.Add('Expected a Gmail JSON response.');
            Exit;
          end;
        m := 0;
        while (m < CkJsonObject_SizeOfArray(reply,'messages')) do
          begin
            CkJsonObject_putI(reply,m);
            success := CkHashtable_AddInt(ids,CkJsonObject__stringOf(reply,'messages[i].id'),1);
            if (success <> True) then
              begin
                Memo1.Lines.Add(CkHashtable__lastErrorText(ids));
                Exit;
              end;
            m := m + 1;
          end;

        pageToken := '';
        if (CkJsonObject_JsonTypeOf(reply,'nextPageToken') = 1) then
          begin
            pageToken := CkJsonObject__stringOf(reply,'nextPageToken');
          end;
        more := pageToken <> '';
      end;

  end;

messages := CkJsonObject_Create();
success := CkJsonObject_ObjectOf2(state,'messages',messages);
if (success <> True) then
  begin
    Memo1.Lines.Add(CkJsonObject__lastErrorText(state));
    Exit;
  end;
//  Message refresh order is unimportant. GetKeys appends keys to this new table.
messageIds := CkStringTable_Create();
success := CkHashtable_GetKeys(ids,messageIds);
if (success <> True) then
  begin
    Memo1.Lines.Add(CkHashtable__lastErrorText(ids));
    Exit;
  end;
cachedMessage := CkJsonObject_Create();
i := 0;
while (i < CkStringTable_getCount(messageIds)) do
  begin
    messageId := CkStringTable__stringAt(messageIds,i);
    CkStringBuilder_SetString(url,'https://gmail.googleapis.com/gmail/v1/users/me/messages/');
    CkStringBuilder_Append(url,CkHttp__urlEncode(http,messageId));
    CkStringBuilder_Append(url,'?format=minimal&fields=id,threadId,labelIds');
    success := CkHttp_HttpNoBody(http,'GET',CkStringBuilder__getAsString(url),resp);
    if (CkHttpResponse_getStatusCode(resp) = 404) then
      begin
        if (CkJsonObject_HasMember(messages,messageId) = True) then
          begin
            success := CkJsonObject_Delete(messages,messageId);
            if (success <> True) then
              begin
                Memo1.Lines.Add(CkJsonObject__lastErrorText(messages));
                Exit;
              end;
          end;
        Memo1.Lines.Add('Removed from cache: ' + messageId);
      end
    else
      begin
        if (CkHttpResponse_getStatusCode(resp) = 0) then
          begin
            Memo1.Lines.Add('Gmail did not return an HTTP response.');
            Exit;
          end;
        if ((success <> True) or (CkHttpResponse_getStatusCode(resp) < 200) or (CkHttpResponse_getStatusCode(resp) >= 300)) then
          begin
            Memo1.Lines.Add('Gmail HTTP ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
            success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
            if (success = True) then
              begin
                Memo1.Lines.Add(CkJsonObject__stringOf(reply,'error.message'));
              end;
            Exit;
          end;
        success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
        if (success <> True) then
          begin
            Memo1.Lines.Add('Expected a Gmail JSON response.');
            Exit;
          end;
        if (CkJsonObject_StringOfEquals(reply,'id',messageId,True) <> True) then
          begin
            Memo1.Lines.Add('Unexpected message ID in the response.');
            Exit;
          end;
        success := CkJsonObject_UpdateNewObject(messages,messageId);
        if (success <> True) then
          begin
            Memo1.Lines.Add(CkJsonObject__lastErrorText(messages));
            Exit;
          end;
        success := CkJsonObject_ObjectOf2(messages,messageId,cachedMessage);
        if (success <> True) then
          begin
            Memo1.Lines.Add(CkJsonObject__lastErrorText(messages));
            Exit;
          end;
        success := CkJsonObject_Load(cachedMessage,CkJsonObject__emit(reply));
        if (success <> True) then
          begin
            Memo1.Lines.Add(CkJsonObject__lastErrorText(cachedMessage));
            Exit;
          end;
        Memo1.Lines.Add('Cached message: ' + messageId);
      end;
    i := i + 1;
  end;

success := CkJsonObject_UpdateString(state,'historyId',checkpoint);
if (success <> True) then
  begin
    Memo1.Lines.Add(CkJsonObject__lastErrorText(state));
    Exit;
  end;
//  Prepare the complete replacement before moving the last committed file.
success := CkJsonObject_WriteFile(state,'gmail-sync.json.new');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not write the replacement file.');
    Exit;
  end;
if (CkFileAccess_FileExists(files,'gmail-sync.json') = True) then
  begin
    if (CkFileAccess_FileExists(files,'gmail-sync.json.previous') = True) then
      begin
        success := CkFileAccess_FileDelete(files,'gmail-sync.json.previous');
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not rotate the previous backup.');
            Exit;
          end;
      end;
    success := CkFileAccess_FileRename(files,'gmail-sync.json','gmail-sync.json.previous');
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not retain the previous complete file.');
        Exit;
      end;
  end;
success := CkFileAccess_FileRename(files,'gmail-sync.json.new','gmail-sync.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not commit the replacement. The previous complete file is retained.');
    Exit;
  end;
Memo1.Lines.Add('Synchronization committed. Cached messages: ' + IntToStr(CkJsonObject_getSize(messages)));
Memo1.Lines.Add('Saved history ID: ' + checkpoint);

CkJsonObject_Dispose(token);
CkHttp_Dispose(http);
CkHttpResponse_Dispose(resp);
CkJsonObject_Dispose(reply);
CkFileAccess_Dispose(files);
CkJsonObject_Dispose(state);
CkHashtable_Dispose(ids);
CkStringBuilder_Dispose(baseUrl);
CkStringBuilder_Dispose(url);
    CkStringTable_Dispose(changeTypes);
    CkJsonObject_Dispose(record);
    CkStringBuilder_Dispose(eventPath);
CkJsonObject_Dispose(messages);
CkStringTable_Dispose(messageIds);
CkJsonObject_Dispose(cachedMessage);