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

VBScript
Dim fso, outFile
Set fso = CreateObject("Scripting.FileSystemObject")
'Create a Unicode (utf-16) output text file.
Set outFile = fso.CreateTextFile("output.txt", True, True)

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.
set token = CreateObject("Chilkat.JsonObject")
token.Strict = 1
success = token.LoadFile("qa_data/tokens/outlookContacts.json")
If (success <> 1) Then
    outFile.WriteLine("Could not read the private contacts token cache.")
    WScript.Quit
End If

If ((token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token","",1) = 1)) Then
    outFile.WriteLine("Expected a nonempty access_token in the JSON.")
    WScript.Quit
End If

set http = CreateObject("Chilkat.Http")
http.AuthToken = token.StringOf("access_token")
http.RequireSslCertVerify = 1
http.FollowRedirects = 0
http.ConnectTimeout = 20
http.ReadTimeout = 30
http.SetRequestHeader "Accept","application/json"
set resp = CreateObject("Chilkat.HttpResponse")
set result = CreateObject("Chilkat.JsonObject")
result.Strict = 1
http.SetRequestHeader "Prefer","IdType=""ImmutableId"", odata.maxpagesize=50"
folderId = "YOUR_CONTACT_FOLDER_ID"
set fac = CreateObject("Chilkat.FileAccess")
success = fac.DirEnsureExists("qa_data/outlookContacts")
If (success <> 1) Then
    outFile.WriteLine("Could not create the private synchronization directory.")
    WScript.Quit
End If

cachePath = "qa_data/outlookContacts/contacts-sync.json"
backupPath = "qa_data/outlookContacts/contacts-sync.json.bak"
set state = CreateObject("Chilkat.JsonObject")
state.Strict = 1
If (fac.FileExists(cachePath) = 1) Then
    success = state.LoadFile(cachePath)
    If (success <> 1) Then
        outFile.WriteLine("Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing.")
        WScript.Quit
    End If

    If ((state.JsonTypeOf("resumeUrl") <> 1) Or (state.StringOfEquals("resumeUrl","",1) = 1)) Then
        outFile.WriteLine("Expected a nonempty resumeUrl in the JSON.")
        WScript.Quit
    End If

    If ((state.JsonTypeOf("folderId") <> 1) Or (state.StringOfEquals("folderId","",1) = 1)) Then
        outFile.WriteLine("Expected a nonempty folderId in the JSON.")
        WScript.Quit
    End If

    If (state.StringOfEquals("folderId",folderId,1) <> 1) Then
        outFile.WriteLine("This checkpoint belongs to another folder. Use a separate cache.")
        WScript.Quit
    End If

    If (state.JsonTypeOf("items") <> 3) Then
        outFile.WriteLine("Expected an items object in the checkpoint.")
        WScript.Quit
    End If

Else
    set endpoint = CreateObject("Chilkat.StringBuilder")
    success = endpoint.Append("https://graph.microsoft.com/v1.0/me/contactFolders/")
    success = endpoint.Append(http.UrlEncode(folderId))
    success = endpoint.Append("/contacts/delta?$select=id,displayName,emailAddresses,mobilePhone")
    success = state.UpdateString("folderId",folderId)
    success = state.UpdateString("resumeUrl",endpoint.GetAsString())
    success = state.UpdateNewObject("items")
End If

set hash = CreateObject("Chilkat.Crypt2")
hash.HashAlgorithm = "sha256"
hash.Charset = "utf-8"
hash.EncodingMode = "hex"
set link = CreateObject("Chilkat.StringBuilder")
set itemPath = CreateObject("Chilkat.StringBuilder")
set seenLinks = CreateObject("Chilkat.Hashtable")
set previous = CreateObject("Chilkat.JsonObject")
previous.Strict = 1
pageCount = 0
Do While (pageCount < 100)
    url = state.StringOf("resumeUrl")
    link.Clear 
    success = link.Append(url)
    If (link.StartsWith("https://graph.microsoft.com/v1.0/",1) <> 1) Then
        outFile.WriteLine("Unexpected continuation host or API version; no request sent.")
        WScript.Quit
    End If

    If (seenLinks.Contains(url) = 1) Then
        outFile.WriteLine("Repeated continuation URL; stopping.")
        WScript.Quit
    End If

    success = seenLinks.AddInt(url,1)
    success = http.HttpNoBody("GET",url,resp)
    '  A false result can still include an HTTP error response.
    If ((success <> 1) And (resp.StatusCode = 0)) Then
        outFile.WriteLine("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
        WScript.Quit
    End If

    If (resp.StatusCode <> 200) Then
        outFile.WriteLine("Unexpected HTTP status: " & resp.StatusCode)
        outFile.WriteLine("Request ID: " & resp.GetHeaderField("request-id"))
        If (resp.StatusCode = 429) Then
            outFile.WriteLine("Retry-After: " & resp.GetHeaderField("Retry-After"))
        End If

        If (resp.StatusCode = 401) Then
            outFile.WriteLine("Refresh the Graph access token or authorize again.")
        End If

        WScript.Quit
    End If

    success = result.Load(resp.BodyStr)
    If (success <> 1) Then
        outFile.WriteLine("Expected a well-formed JSON response.")
        WScript.Quit
    End If

    If (result.JsonTypeOf("value") <> 4) Then
        outFile.WriteLine("Expected a value array; checkpoint unchanged.")
        WScript.Quit
    End If

    '  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
        resumeUrl = result.StringOf("""@odata.nextLink""")
    Else
        If ((deltaType <> 1) Or (nextType <> -1)) Then
            outFile.WriteLine("Invalid delta continuation; checkpoint unchanged.")
            WScript.Quit
        End If

        resumeUrl = result.StringOf("""@odata.deltaLink""")
        finished = 1
    End If

    link.Clear 
    success = link.Append(resumeUrl)
    If (link.StartsWith("https://graph.microsoft.com/v1.0/",1) <> 1) Then
        outFile.WriteLine("Invalid continuation URL; checkpoint unchanged.")
        WScript.Quit
    End If

    success = previous.Load(state.Emit())
    If (success <> 1) Then
        outFile.WriteLine("Could not snapshot the previous checkpoint.")
        WScript.Quit
    End If

    i = 0
    Do While (i < result.SizeOfArray("value"))
        result.I = i
        If ((result.JsonTypeOf("value[i].id") <> 1) Or (result.StringOfEquals("value[i].id","",1) = 1)) Then
            outFile.WriteLine("Expected a nonempty value[i].id in the JSON.")
            WScript.Quit
        End If

        contactId = result.StringOf("value[i].id")
        itemKey = hash.HashStringENC(contactId)
        If (hash.LastMethodSuccess <> 1) Then
            outFile.WriteLine("Could not form a local record key.")
            WScript.Quit
        End If

        '  Hash only for a JSON-safe local key. Preserve the original opaque ID in the record.
        itemPath.Clear 
        success = itemPath.Append("items.")
        success = itemPath.Append(itemKey)
        If (state.JsonTypeOf(itemPath.GetAsString()) <> 3) Then
            success = state.UpdateNewObject(itemPath.GetAsString())
        End If

        success = itemPath.Append(".")
        state.PathPrefix = itemPath.GetAsString()
        success = state.UpdateString("id",contactId)
        If (result.JsonTypeOf("value[i].@removed") = 3) Then
            '  Hide records with removed=true from the local folder view.
            success = state.UpdateBool("removed",1)
            outFile.WriteLine("Removed from the local view: " & contactId)
        Else
            success = state.UpdateBool("removed",0)
            displayNameType = result.JsonTypeOf("value[i].displayName")
            If (displayNameType = 1) Then
                success = state.UpdateString("displayName",result.StringOf("value[i].displayName"))
            Else
                If (displayNameType = 6) Then
                    success = state.UpdateNull("displayName")
                Else
                    If (displayNameType <> -1) Then
                        outFile.WriteLine("Invalid contact field; checkpoint unchanged.")
                        WScript.Quit
                    End If

                End If

            End If

            mobilePhoneType = result.JsonTypeOf("value[i].mobilePhone")
            If (mobilePhoneType = 1) Then
                success = state.UpdateString("mobilePhone",result.StringOf("value[i].mobilePhone"))
            Else
                If (mobilePhoneType = 6) Then
                    success = state.UpdateNull("mobilePhone")
                Else
                    If (mobilePhoneType <> -1) Then
                        outFile.WriteLine("Invalid contact field; checkpoint unchanged.")
                        WScript.Quit
                    End If

                End If

            End If

            emailType = result.JsonTypeOf("value[i].emailAddresses")
            If (emailType = 4) Then
                '  Replace this collection when present, including an empty array that clears it.
                success = state.UpdateNewArray("emailAddresses")
                j = 0
                Do While (j < result.SizeOfArray("value[i].emailAddresses"))
                    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
                        outFile.WriteLine("Expected a nonempty value[i].emailAddresses[j].address in the JSON.")
                        WScript.Quit
                    End If

                    success = state.UpdateString("emailAddresses[j].address",result.StringOf("value[i].emailAddresses[j].address"))
                    If (result.JsonTypeOf("value[i].emailAddresses[j].name") = 1) Then
                        success = state.UpdateString("emailAddresses[j].name",result.StringOf("value[i].emailAddresses[j].name"))
                    End If

                    j = j + 1
                Loop
            Else
                If (emailType <> -1) Then
                    outFile.WriteLine("Invalid email collection; checkpoint unchanged.")
                    WScript.Quit
                End If

            End If

            state.PathPrefix = ""
            outFile.WriteLine("Updated local contact: " & contactId)
        End If

        state.PathPrefix = ""
        i = i + 1
    Loop
    success = state.UpdateString("resumeUrl",resumeUrl)
    success = 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
        outFile.WriteLine("Could not back up the previous checkpoint; no replacement attempted.")
        WScript.Quit
    End If

    success = state.WriteFile(cachePath)
    If (success <> 1) Then
        outFile.WriteLine("Checkpoint write failed. Restore the private .bak before continuing.")
        WScript.Quit
    End If

    pageCount = pageCount + 1
    If (finished = 1) Then
        outFile.WriteLine("Synchronization round complete; saved the delta link for the next run.")
        WScript.Quit
    End If

Loop
outFile.WriteLine("Paused after 100 pages; the saved nextLink resumes on the next run.")

outFile.Close