Sample code for 30+ languages & platforms
Delphi ActiveX Requires Chilkat v11.6.0+

Outlook Contacts: Synchronize Contacts in a Folder with Delta Queries

See more Outlook Contact Examples

Build a local contact projection for one folder, then retrieve incremental changes on later runs. Supply a folder ID from folder enumeration or a contact's parentFolderId. This uses /me/contactFolders/{id}/contacts/delta, not a calendar-style date window. The initial $select requests id, displayName, emailAddresses, and mobilePhone. The saved projection is not a full contact archive.

Follow exact nextLink URLs within a round; save the final deltaLink for the next round. Do not rebuild opaque tokens or re-add query options. Preserve the same ID preference and field selection. Contact IDs remain strings; their hashes are only JSON-safe local keys. @removed records are tombstones (removed=true) to exclude from this local folder view. A removal can reflect a move out of the folder, not necessarily a global deletion. Repeated changes update the same record; omitted fields are retained, explicit nulls clear scalar values, and present email arrays replace the saved array.

The checkpoint stores contact data and the continuation URL together, with a backup of the previous matching pair before replacement. HTTP/validation failures do not advance it. If the main file is damaged, recover the private .bak pair. Replaying a page is safe for these upserts and tombstones. Production storage should atomically commit data and cursor. Use one writer and a separate cache for each account/folder/projection. The sample rejects a different folder ID and pauses after 100 pages with its nextLink saved. A rejected or expired sync state requires a new baseline and deliberate reconciliation of the old view.

Delegated permission: Contacts.Read.

Uses Microsoft Graph v1.0 for contacts stored in an Outlook.com or Microsoft 365 mailbox. These are personal mailbox contacts, not Microsoft Entra directory users, organizational contacts (/contacts), or the People API. Obtain a delegated token with the contacts OAuth2 example; the cache is qa_data/tokens/outlookContacts.json. A token for Calendar, SMTP, or another resource without the needed Graph contacts permission is insufficient.

/me requires a signed-in user. An authorized unattended Microsoft 365 application instead needs application permissions and administrator consent, and targets /users/{id-or-UPN}. App-only access does not apply to personal Outlook.com mailboxes. Shared folders require actual sharing rights and Contacts.Read.Shared or Contacts.ReadWrite.Shared delegated consent. The examples target the global cloud.

HTTP methods can return false for an HTTP error as well as a connection failure. The code distinguishes those cases and checks the expected status before reading JSON. For 401, refresh the access token or authorize again; for 403, check permissions, mailbox access, and tenant policy. For 429, honor Retry-After before a bounded retry. Do not automatically repeat a write after an uncertain outcome. Keep detailed errors and contact data private.

Microsoft documentation

Chilkat Delphi ActiveX Downloads

Delphi ActiveX
var
success: Integer;
token: TChilkatJsonObject;
http: TChilkatHttp;
resp: TChilkatHttpResponse;
result: TChilkatJsonObject;
folderId: WideString;
fac: TCkFileAccess;
cachePath: WideString;
backupPath: WideString;
state: TChilkatJsonObject;
endpoint: TChilkatStringBuilder;
hash: TChilkatCrypt2;
link: TChilkatStringBuilder;
itemPath: TChilkatStringBuilder;
seenLinks: TCkStringArray;
previous: TChilkatJsonObject;
pageCount: Integer;
url: WideString;
nextType: Integer;
deltaType: Integer;
finished: Integer;
resumeUrl: WideString;
i: Integer;
contactId: WideString;
itemKey: WideString;
displayNameType: Integer;
mobilePhoneType: Integer;
emailType: Integer;
j: Integer;

begin
success := 0;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success := 0;
//  Obtain a delegated Microsoft Graph token using the contacts authorization example.
//  See Authorize Outlook Contacts with OAuth2 and PKCE.
token := TChilkatJsonObject.Create(Self);
token.Strict := 1;
success := token.LoadFile('qa_data/tokens/outlookContacts.json');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not read the private contacts token cache.');
    Exit;
  end;
if ((token.JsonTypeOf('access_token') <> 1) or (token.StringOfEquals('access_token','',1) = 1)) then
  begin
    Memo1.Lines.Add('Expected a nonempty access_token in the JSON.');
    Exit;
  end;
http := TChilkatHttp.Create(Self);
http.AuthToken := token.StringOf('access_token');
http.RequireSslCertVerify := 1;
http.FollowRedirects := 0;
http.ConnectTimeout := 20;
http.ReadTimeout := 30;
http.SetRequestHeader('Accept','application/json');
resp := TChilkatHttpResponse.Create(Self);
result := TChilkatJsonObject.Create(Self);
result.Strict := 1;
http.SetRequestHeader('Prefer','IdType="ImmutableId", odata.maxpagesize=50');
folderId := 'YOUR_CONTACT_FOLDER_ID';
fac := TCkFileAccess.Create(Self);
success := fac.DirEnsureExists('qa_data/outlookContacts');
if (success <> 1) then
  begin
    Memo1.Lines.Add('Could not create the private synchronization directory.');
    Exit;
  end;
cachePath := 'qa_data/outlookContacts/contacts-sync.json';
backupPath := 'qa_data/outlookContacts/contacts-sync.json.bak';
state := TChilkatJsonObject.Create(Self);
state.Strict := 1;
if (fac.FileExists(cachePath) = 1) then
  begin
    success := state.LoadFile(cachePath);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing.');
        Exit;
      end;
    if ((state.JsonTypeOf('resumeUrl') <> 1) or (state.StringOfEquals('resumeUrl','',1) = 1)) then
      begin
        Memo1.Lines.Add('Expected a nonempty resumeUrl in the JSON.');
        Exit;
      end;
    if ((state.JsonTypeOf('folderId') <> 1) or (state.StringOfEquals('folderId','',1) = 1)) then
      begin
        Memo1.Lines.Add('Expected a nonempty folderId in the JSON.');
        Exit;
      end;
    if (state.StringOfEquals('folderId',folderId,1) <> 1) then
      begin
        Memo1.Lines.Add('This checkpoint belongs to another folder. Use a separate cache.');
        Exit;
      end;
    if (state.JsonTypeOf('items') <> 3) then
      begin
        Memo1.Lines.Add('Expected an items object in the checkpoint.');
        Exit;
      end;
  end
else
  begin
    endpoint := TChilkatStringBuilder.Create(Self);
    endpoint.Append('https://graph.microsoft.com/v1.0/me/contactFolders/');
    endpoint.Append(http.UrlEncode(folderId));
    endpoint.Append('/contacts/delta?$select=id,displayName,emailAddresses,mobilePhone');
    state.UpdateString('folderId',folderId);
    state.UpdateString('resumeUrl',endpoint.GetAsString());
    state.UpdateNewObject('items');
  end;
hash := TChilkatCrypt2.Create(Self);
hash.HashAlgorithm := 'sha256';
hash.Charset := 'utf-8';
hash.EncodingMode := 'hex';
link := TChilkatStringBuilder.Create(Self);
itemPath := TChilkatStringBuilder.Create(Self);
seenLinks := TCkStringArray.Create(Self);
previous := TChilkatJsonObject.Create(Self);
previous.Strict := 1;
pageCount := 0;
while (pageCount < 100) do
  begin
    url := state.StringOf('resumeUrl');
    link.Clear();
    link.Append(url);
    if (link.StartsWith('https://graph.microsoft.com/v1.0/',1) <> 1) then
      begin
        Memo1.Lines.Add('Unexpected continuation host or API version; no request sent.');
        Exit;
      end;
    if (seenLinks.Find(url,0) >= 0) then
      begin
        Memo1.Lines.Add('Repeated continuation URL; stopping.');
        Exit;
      end;
    seenLinks.Append(url);
    success := http.HttpNoBody('GET',url,resp.ControlInterface);
    //  A false result can still include an HTTP error response.
    if ((success <> 1) and (resp.StatusCode = 0)) then
      begin
        Memo1.Lines.Add('No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.');
        Exit;
      end;
    if (resp.StatusCode <> 200) then
      begin
        Memo1.Lines.Add('Unexpected HTTP status: ' + IntToStr(resp.StatusCode));
        Memo1.Lines.Add('Request ID: ' + resp.GetHeaderField('request-id'));
        if (resp.StatusCode = 429) then
          begin
            Memo1.Lines.Add('Retry-After: ' + resp.GetHeaderField('Retry-After'));
          end;
        if (resp.StatusCode = 401) then
          begin
            Memo1.Lines.Add('Refresh the Graph access token or authorize again.');
          end;
        Exit;
      end;
    success := result.Load(resp.BodyStr);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Expected a well-formed JSON response.');
        Exit;
      end;
    if (result.JsonTypeOf('value') <> 4) then
      begin
        Memo1.Lines.Add('Expected a value array; checkpoint unchanged.');
        Exit;
      end;
    //  Exactly one continuation member must be a nonempty string.
    nextType := result.JsonTypeOf('"@odata.nextLink"');
    deltaType := result.JsonTypeOf('"@odata.deltaLink"');
    finished := 0;

    if ((nextType = 1) and (deltaType = -1)) then
      begin
        resumeUrl := result.StringOf('"@odata.nextLink"');
      end
    else
      begin
        if ((deltaType <> 1) or (nextType <> -1)) then
          begin
            Memo1.Lines.Add('Invalid delta continuation; checkpoint unchanged.');
            Exit;
          end;
        resumeUrl := result.StringOf('"@odata.deltaLink"');
        finished := 1;
      end;
    link.Clear();
    link.Append(resumeUrl);
    if (link.StartsWith('https://graph.microsoft.com/v1.0/',1) <> 1) then
      begin
        Memo1.Lines.Add('Invalid continuation URL; checkpoint unchanged.');
        Exit;
      end;
    success := previous.Load(state.Emit());
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Could not snapshot the previous checkpoint.');
        Exit;
      end;
    i := 0;
    while (i < result.SizeOfArray('value')) do
      begin
        result.I := i;
        if ((result.JsonTypeOf('value[i].id') <> 1) or (result.StringOfEquals('value[i].id','',1) = 1)) then
          begin
            Memo1.Lines.Add('Expected a nonempty value[i].id in the JSON.');
            Exit;
          end;
        contactId := result.StringOf('value[i].id');
        itemKey := hash.HashStringENC(contactId);
        if (hash.LastMethodSuccess <> 1) then
          begin
            Memo1.Lines.Add('Could not form a local record key.');
            Exit;
          end;
        //  Hash only for a JSON-safe local key. Preserve the original opaque ID in the record.
        itemPath.Clear();
        itemPath.Append('items.');
        itemPath.Append(itemKey);
        if (state.JsonTypeOf(itemPath.GetAsString()) <> 3) then
          begin
            state.UpdateNewObject(itemPath.GetAsString());
          end;
        itemPath.Append('.');
        state.PathPrefix := itemPath.GetAsString();
        state.UpdateString('id',contactId);
        if (result.JsonTypeOf('value[i].@removed') = 3) then
          begin
            //  Hide records with removed=true from the local folder view.
            state.UpdateBool('removed',1);
            Memo1.Lines.Add('Removed from the local view: ' + contactId);
          end
        else
          begin
            state.UpdateBool('removed',0);
            displayNameType := result.JsonTypeOf('value[i].displayName');
            if (displayNameType = 1) then
              begin
                state.UpdateString('displayName',result.StringOf('value[i].displayName'));
              end
            else
              begin
                if (displayNameType = 6) then
                  begin
                    state.UpdateNull('displayName');
                  end
                else
                  begin
                    if (displayNameType <> -1) then
                      begin
                        Memo1.Lines.Add('Invalid contact field; checkpoint unchanged.');
                        Exit;
                      end;
                  end;
              end;
            mobilePhoneType := result.JsonTypeOf('value[i].mobilePhone');
            if (mobilePhoneType = 1) then
              begin
                state.UpdateString('mobilePhone',result.StringOf('value[i].mobilePhone'));
              end
            else
              begin
                if (mobilePhoneType = 6) then
                  begin
                    state.UpdateNull('mobilePhone');
                  end
                else
                  begin
                    if (mobilePhoneType <> -1) then
                      begin
                        Memo1.Lines.Add('Invalid contact field; checkpoint unchanged.');
                        Exit;
                      end;
                  end;
              end;
            emailType := result.JsonTypeOf('value[i].emailAddresses');
            if (emailType = 4) then
              begin
                //  Replace this collection when present, including an empty array that clears it.
                state.UpdateNewArray('emailAddresses');
                j := 0;
                while (j < result.SizeOfArray('value[i].emailAddresses')) do
                  begin
                    result.J := j;
                    state.J := j;
                    if ((result.JsonTypeOf('value[i].emailAddresses[j].address') <> 1) or (result.StringOfEquals('value[i].emailAddresses[j].address','',1) = 1)) then
                      begin
                        Memo1.Lines.Add('Expected a nonempty value[i].emailAddresses[j].address in the JSON.');
                        Exit;
                      end;
                    state.UpdateString('emailAddresses[j].address',result.StringOf('value[i].emailAddresses[j].address'));
                    if (result.JsonTypeOf('value[i].emailAddresses[j].name') = 1) then
                      begin
                        state.UpdateString('emailAddresses[j].name',result.StringOf('value[i].emailAddresses[j].name'));
                      end;
                    j := j + 1;
                  end;

              end
            else
              begin
                if (emailType <> -1) then
                  begin
                    Memo1.Lines.Add('Invalid email collection; checkpoint unchanged.');
                    Exit;
                  end;
              end;
            state.PathPrefix := '';
            Memo1.Lines.Add('Updated local contact: ' + contactId);
          end;
        state.PathPrefix := '';
        i := i + 1;
      end;

    state.UpdateString('resumeUrl',resumeUrl);
    state.UpdateBool('roundComplete',finished);
    //  Save the data and cursor in one document. The backup contains the matching previous pair.
    success := previous.WriteFile(backupPath);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Could not back up the previous checkpoint; no replacement attempted.');
        Exit;
      end;
    success := state.WriteFile(cachePath);
    if (success <> 1) then
      begin
        Memo1.Lines.Add('Checkpoint write failed. Restore the private .bak before continuing.');
        Exit;
      end;
    pageCount := pageCount + 1;
    if (finished = 1) then
      begin
        Memo1.Lines.Add('Synchronization round complete; saved the delta link for the next run.');
        Exit;
      end;
  end;

Memo1.Lines.Add('Paused after 100 pages; the saved nextLink resumes on the next run.');