Sample code for 30+ languages & platforms
AutoIt 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 AutoIt Downloads

AutoIt
Local $bSuccess = False

;  Assumes Chilkat is unlocked. See Global Unlock Sample.
$bSuccess = False
;  Obtain a delegated Microsoft Graph token using the contacts authorization example.
;  See Authorize Outlook Contacts with OAuth2 and PKCE.
$oToken = ObjCreate("Chilkat.JsonObject")
$oToken.Strict = True
$bSuccess = $oToken.LoadFile("qa_data/tokens/outlookContacts.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not read the private contacts token cache." & @CRLF)
    Exit
EndIf

If (($oToken.JsonTypeOf("access_token") <> 1) Or ($oToken.StringOfEquals("access_token","",True) = True)) Then
    ConsoleWrite("Expected a nonempty access_token in the JSON." & @CRLF)
    Exit
EndIf

$oHttp = ObjCreate("Chilkat.Http")
$oHttp.AuthToken = $oToken.StringOf("access_token")
$oHttp.RequireSslCertVerify = True
$oHttp.FollowRedirects = False
$oHttp.ConnectTimeout = 20
$oHttp.ReadTimeout = 30
$oHttp.SetRequestHeader "Accept","application/json"
$oResp = ObjCreate("Chilkat.HttpResponse")
$oResult = ObjCreate("Chilkat.JsonObject")
$oResult.Strict = True
$oHttp.SetRequestHeader "Prefer","IdType=""ImmutableId"", odata.maxpagesize=50"
Local $sFolderId = "YOUR_CONTACT_FOLDER_ID"
$oFac = ObjCreate("Chilkat.FileAccess")
$bSuccess = $oFac.DirEnsureExists("qa_data/outlookContacts")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not create the private synchronization directory." & @CRLF)
    Exit
EndIf

Local $sCachePath = "qa_data/outlookContacts/contacts-sync.json"
Local $sBackupPath = "qa_data/outlookContacts/contacts-sync.json.bak"
$oState = ObjCreate("Chilkat.JsonObject")
$oState.Strict = True
If ($oFac.FileExists($sCachePath) = True) Then
    $bSuccess = $oState.LoadFile($sCachePath)
    If ($bSuccess <> True) Then
        ConsoleWrite("Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing." & @CRLF)
        Exit
    EndIf

    If (($oState.JsonTypeOf("resumeUrl") <> 1) Or ($oState.StringOfEquals("resumeUrl","",True) = True)) Then
        ConsoleWrite("Expected a nonempty resumeUrl in the JSON." & @CRLF)
        Exit
    EndIf

    If (($oState.JsonTypeOf("folderId") <> 1) Or ($oState.StringOfEquals("folderId","",True) = True)) Then
        ConsoleWrite("Expected a nonempty folderId in the JSON." & @CRLF)
        Exit
    EndIf

    If ($oState.StringOfEquals("folderId",$sFolderId,True) <> True) Then
        ConsoleWrite("This checkpoint belongs to another folder. Use a separate cache." & @CRLF)
        Exit
    EndIf

    If ($oState.JsonTypeOf("items") <> 3) Then
        ConsoleWrite("Expected an items object in the checkpoint." & @CRLF)
        Exit
    EndIf

Else
    $oEndpoint = ObjCreate("Chilkat.StringBuilder")
    $oEndpoint.Append("https://graph.microsoft.com/v1.0/me/contactFolders/")
    $oEndpoint.Append($oHttp.UrlEncode($sFolderId))
    $oEndpoint.Append("/contacts/delta?$select=id,displayName,emailAddresses,mobilePhone")
    $oState.UpdateString("folderId",$sFolderId)
    $oState.UpdateString("resumeUrl",$oEndpoint.GetAsString())
    $oState.UpdateNewObject("items")
EndIf

$oHash = ObjCreate("Chilkat.Crypt2")
$oHash.HashAlgorithm = "sha256"
$oHash.Charset = "utf-8"
$oHash.EncodingMode = "hex"
$oLink = ObjCreate("Chilkat.StringBuilder")
$oItemPath = ObjCreate("Chilkat.StringBuilder")
$oSeenLinks = ObjCreate("Chilkat.Hashtable")
$oPrevious = ObjCreate("Chilkat.JsonObject")
$oPrevious.Strict = True
Local $iPageCount = 0
While ($iPageCount < 100)
Local $sUrl = $oState.StringOf("resumeUrl")
    $oLink.Clear 
    $oLink.Append($sUrl)
    If ($oLink.StartsWith("https://graph.microsoft.com/v1.0/",True) <> True) Then
        ConsoleWrite("Unexpected continuation host or API version; no request sent." & @CRLF)
        Exit
    EndIf

    If ($oSeenLinks.Contains($sUrl) = True) Then
        ConsoleWrite("Repeated continuation URL; stopping." & @CRLF)
        Exit
    EndIf

    $oSeenLinks.AddInt($sUrl,1)
    $bSuccess = $oHttp.HttpNoBody("GET",$sUrl,$oResp)
    ;  A false result can still include an HTTP error response.
    If (($bSuccess <> True) And ($oResp.StatusCode = 0)) Then
        ConsoleWrite("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying." & @CRLF)
        Exit
    EndIf

    If ($oResp.StatusCode <> 200) Then
        ConsoleWrite("Unexpected HTTP status: " & $oResp.StatusCode & @CRLF)
        ConsoleWrite("Request ID: " & $oResp.GetHeaderField("request-id") & @CRLF)
        If ($oResp.StatusCode = 429) Then
            ConsoleWrite("Retry-After: " & $oResp.GetHeaderField("Retry-After") & @CRLF)
        EndIf

        If ($oResp.StatusCode = 401) Then
            ConsoleWrite("Refresh the Graph access token or authorize again." & @CRLF)
        EndIf

        Exit
    EndIf

    $bSuccess = $oResult.Load($oResp.BodyStr)
    If ($bSuccess <> True) Then
        ConsoleWrite("Expected a well-formed JSON response." & @CRLF)
        Exit
    EndIf

    If ($oResult.JsonTypeOf("value") <> 4) Then
        ConsoleWrite("Expected a value array; checkpoint unchanged." & @CRLF)
        Exit
    EndIf

    ;  Exactly one continuation member must be a nonempty string.
Local $iNextType = $oResult.JsonTypeOf("""@odata.nextLink""")
Local $iDeltaType = $oResult.JsonTypeOf("""@odata.deltaLink""")
Local $bFinished = False
Local $sResumeUrl
    If (($iNextType = 1) And ($iDeltaType = -1)) Then
        $sResumeUrl = $oResult.StringOf("""@odata.nextLink""")
    Else
        If (($iDeltaType <> 1) Or ($iNextType <> -1)) Then
            ConsoleWrite("Invalid delta continuation; checkpoint unchanged." & @CRLF)
            Exit
        EndIf

        $sResumeUrl = $oResult.StringOf("""@odata.deltaLink""")
        $bFinished = True
    EndIf

    $oLink.Clear 
    $oLink.Append($sResumeUrl)
    If ($oLink.StartsWith("https://graph.microsoft.com/v1.0/",True) <> True) Then
        ConsoleWrite("Invalid continuation URL; checkpoint unchanged." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oPrevious.Load($oState.Emit())
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not snapshot the previous checkpoint." & @CRLF)
        Exit
    EndIf

Local $i = 0
    While ($i < $oResult.SizeOfArray("value"))
        $oResult.I = $i
        If (($oResult.JsonTypeOf("value[i].id") <> 1) Or ($oResult.StringOfEquals("value[i].id","",True) = True)) Then
            ConsoleWrite("Expected a nonempty value[i].id in the JSON." & @CRLF)
            Exit
        EndIf

Local $sContactId = $oResult.StringOf("value[i].id")
Local $sItemKey = $oHash.HashStringENC($sContactId)
        If ($oHash.LastMethodSuccess <> True) Then
            ConsoleWrite("Could not form a local record key." & @CRLF)
            Exit
        EndIf

        ;  Hash only for a JSON-safe local key. Preserve the original opaque ID in the record.
        $oItemPath.Clear 
        $oItemPath.Append("items.")
        $oItemPath.Append($sItemKey)
        If ($oState.JsonTypeOf($oItemPath.GetAsString()) <> 3) Then
            $oState.UpdateNewObject($oItemPath.GetAsString())
        EndIf

        $oItemPath.Append(".")
        $oState.PathPrefix = $oItemPath.GetAsString()
        $oState.UpdateString("id",$sContactId)
        If ($oResult.JsonTypeOf("value[i].@removed") = 3) Then
            ;  Hide records with removed=true from the local folder view.
            $oState.UpdateBool("removed",True)
            ConsoleWrite("Removed from the local view: " & $sContactId & @CRLF)
        Else
            $oState.UpdateBool("removed",False)
Local $iDisplayNameType = $oResult.JsonTypeOf("value[i].displayName")
            If ($iDisplayNameType = 1) Then
                $oState.UpdateString("displayName",$oResult.StringOf("value[i].displayName"))
            Else
                If ($iDisplayNameType = 6) Then
                    $oState.UpdateNull("displayName")
                Else
                    If ($iDisplayNameType <> -1) Then
                        ConsoleWrite("Invalid contact field; checkpoint unchanged." & @CRLF)
                        Exit
                    EndIf

                EndIf

            EndIf

Local $iMobilePhoneType = $oResult.JsonTypeOf("value[i].mobilePhone")
            If ($iMobilePhoneType = 1) Then
                $oState.UpdateString("mobilePhone",$oResult.StringOf("value[i].mobilePhone"))
            Else
                If ($iMobilePhoneType = 6) Then
                    $oState.UpdateNull("mobilePhone")
                Else
                    If ($iMobilePhoneType <> -1) Then
                        ConsoleWrite("Invalid contact field; checkpoint unchanged." & @CRLF)
                        Exit
                    EndIf

                EndIf

            EndIf

Local $iEmailType = $oResult.JsonTypeOf("value[i].emailAddresses")
            If ($iEmailType = 4) Then
                ;  Replace this collection when present, including an empty array that clears it.
                $oState.UpdateNewArray("emailAddresses")
Local $iJ = 0
                While ($iJ < $oResult.SizeOfArray("value[i].emailAddresses"))
                    $oResult.J = $iJ
                    $oState.J = $iJ
                    If (($oResult.JsonTypeOf("value[i].emailAddresses[j].address") <> 1) Or ($oResult.StringOfEquals("value[i].emailAddresses[j].address","",True) = True)) Then
                        ConsoleWrite("Expected a nonempty value[i].emailAddresses[j].address in the JSON." & @CRLF)
                        Exit
                    EndIf

                    $oState.UpdateString("emailAddresses[j].address",$oResult.StringOf("value[i].emailAddresses[j].address"))
                    If ($oResult.JsonTypeOf("value[i].emailAddresses[j].name") = 1) Then
                        $oState.UpdateString("emailAddresses[j].name",$oResult.StringOf("value[i].emailAddresses[j].name"))
                    EndIf

                    $iJ = $iJ + 1
                Wend
            Else
                If ($iEmailType <> -1) Then
                    ConsoleWrite("Invalid email collection; checkpoint unchanged." & @CRLF)
                    Exit
                EndIf

            EndIf

            $oState.PathPrefix = ""
            ConsoleWrite("Updated local contact: " & $sContactId & @CRLF)
        EndIf

        $oState.PathPrefix = ""
        $i = $i + 1
    Wend
    $oState.UpdateString("resumeUrl",$sResumeUrl)
    $oState.UpdateBool("roundComplete",$bFinished)
    ;  Save the data and cursor in one document. The backup contains the matching previous pair.
    $bSuccess = $oPrevious.WriteFile($sBackupPath)
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not back up the previous checkpoint; no replacement attempted." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oState.WriteFile($sCachePath)
    If ($bSuccess <> True) Then
        ConsoleWrite("Checkpoint write failed. Restore the private .bak before continuing." & @CRLF)
        Exit
    EndIf

    $iPageCount = $iPageCount + 1
    If ($bFinished = True) Then
        ConsoleWrite("Synchronization round complete; saved the delta link for the next run." & @CRLF)
        Exit
    EndIf

Wend
ConsoleWrite("Paused after 100 pages; the saved nextLink resumes on the next run." & @CRLF)