Outlook Mail: Create a Folder Path-to-ID Map
See more Outlook Examples
Traverse the root and each child-folder collection, following pagination at every level, then save a Chilkat Hashtable as XML. Queue entries keep URLs and parent paths separately. Literal percent signs and slashes in display names become %25 and %2F in map keys; this is a local path convention, not a Graph URL. Duplicate keys stop the example instead of silently overwriting an ID.
The map is an account-specific snapshot. Use a private filename per mailbox, rebuild after rename/move/create/delete, and use atomic replacement in production. A traversal is not transactionally isolated from concurrent mailbox changes. The example stops at 1000 requests and never saves an incomplete traversal. For standard folders prefer the locale-independent well-known names; the displayed map paths use the actual localized names.
Delegated permission: Mail.ReadBasic.
Uses direct Chilkat.Http calls to Microsoft Graph v1.0 for an Outlook.com or Microsoft 365 online mailbox. Save a current Graph access token as access_token in the private file qa_data/tokens/microsoftGraph.json. Obtain it through the Microsoft identity platform authorization-code flow with PKCE for a public interactive client; request offline_access if a refresh token is needed. Consent to the mail permission stated here. Tokens for SMTP/IMAP/POP, Calendar-only, or Contacts-only access are insufficient.
/me requires a signed-in user and delegated permissions. An unattended Microsoft 365 application instead uses administrator-approved application permissions and /users/{id-or-UPN}; limit it to the intended mailboxes. Client credentials is not available for personal Outlook.com mailboxes. These requests access cloud mailbox data, not local PST files, and do not require Outlook to be running. National clouds require their own authority and Graph hosts.
The code checks the HTTP status separately from transport success and validates JSON before reading it. For 401, refresh or authorize again; for 403, check consent, mailbox access, and policy; for 429, honor Retry-After with a bounded retry. A failed or timed-out write can have an uncertain outcome: reconcile before repeating it. Keep tokens, message content, continuation URLs, and detailed diagnostics private.
Chilkat Delphi DLL Downloads
var
success: Boolean;
replaceCount: Integer;
token: HCkJsonObject;
http: HCkHttp;
resp: HCkHttpResponse;
result: HCkJsonObject;
urls: HCkStringArray;
paths: HCkStringArray;
seenLinks: HCkStringArray;
nextLink: HCkStringBuilder;
segment: HCkStringBuilder;
fullPath: HCkStringBuilder;
childUrl: HCkStringBuilder;
folderMap: HCkHashtable;
queueIndex: Integer;
url: PWideChar;
parentPath: PWideChar;
i: Integer;
folderId: PWideChar;
folderPath: PWideChar;
nextType: Integer;
fac: HCkFileAccess;
mapXml: HCkStringBuilder;
begin
success := False;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success := False;
replaceCount := 0;
// Supply a current Microsoft Graph token with this example's mail permissions.
// Keep the token cache private and refresh expired tokens before running the example.
token := CkJsonObject_Create();
CkJsonObject_putStrict(token,True);
success := CkJsonObject_LoadFile(token,'qa_data/tokens/microsoftGraph.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not read the private Graph token cache.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(token,'access_token') <> 1) or (CkJsonObject_StringOfEquals(token,'access_token','',True) = True)) then
begin
Memo1.Lines.Add('Expected a nonempty access_token in the JSON.');
Exit;
end;
http := CkHttp_Create();
CkHttp_putAuthToken(http,CkJsonObject__stringOf(token,'access_token'));
CkHttp_putRequireSslCertVerify(http,True);
CkHttp_putFollowRedirects(http,False);
CkHttp_putConnectTimeout(http,20);
CkHttp_putReadTimeout(http,60);
CkHttp_SetRequestHeader(http,'Accept','application/json');
resp := CkHttpResponse_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
// Queue each collection URL together with its parent path; no delimiter-packed records.
urls := CkStringArray_Create();
paths := CkStringArray_Create();
CkStringArray_Append(urls,'https://graph.microsoft.com/v1.0/me/mailFolders?includeHiddenFolders=true&$select=id,displayName,childFolderCount&$top=50');
CkStringArray_Append(paths,'');
seenLinks := CkStringArray_Create();
nextLink := CkStringBuilder_Create();
segment := CkStringBuilder_Create();
fullPath := CkStringBuilder_Create();
childUrl := CkStringBuilder_Create();
folderMap := CkHashtable_Create();
queueIndex := 0;
while ((queueIndex < CkStringArray_getLength(urls)) and (queueIndex < 1000)) do
begin
url := CkStringArray__getString(urls,queueIndex);
parentPath := CkStringArray__getString(paths,queueIndex);
CkStringBuilder_SetString(nextLink,url);
if (CkStringBuilder_StartsWith(nextLink,'https://graph.microsoft.com/v1.0/',True) <> True) then
begin
Memo1.Lines.Add('Unexpected pagination host or API version; no request sent.');
Exit;
end;
if (CkStringArray_Find(seenLinks,url,0) >= 0) then
begin
Memo1.Lines.Add('Repeated pagination URL; stopping.');
Exit;
end;
CkStringArray_Append(seenLinks,url);
success := CkHttp_HttpNoBody(http,'GET',url,resp);
// A false result can still include an HTTP error response.
if ((success <> True) and (CkHttpResponse_getStatusCode(resp) = 0)) then
begin
Memo1.Lines.Add('No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.');
Exit;
end;
if (CkHttpResponse_getStatusCode(resp) <> 200) then
begin
Memo1.Lines.Add('Unexpected HTTP status: ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
Memo1.Lines.Add('Request ID: ' + CkHttpResponse__getHeaderField(resp,'request-id'));
if (CkHttpResponse_getStatusCode(resp) = 429) then
begin
Memo1.Lines.Add('Retry-After: ' + CkHttpResponse__getHeaderField(resp,'Retry-After'));
end;
if (CkHttpResponse_getStatusCode(resp) = 401) then
begin
Memo1.Lines.Add('Refresh the Graph access token or authorize again.');
end;
Exit;
end;
success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(resp));
if (success <> True) then
begin
Memo1.Lines.Add('Expected a well-formed JSON response.');
Exit;
end;
if (CkJsonObject_JsonTypeOf(result,'value') <> 4) then
begin
Memo1.Lines.Add('Expected a value array.');
Exit;
end;
i := 0;
while (i < CkJsonObject_SizeOfArray(result,'value')) do
begin
CkJsonObject_putI(result,i);
if ((CkJsonObject_JsonTypeOf(result,'value[i].id') <> 1) or (CkJsonObject_StringOfEquals(result,'value[i].id','',True) = True)) then
begin
Memo1.Lines.Add('Expected a nonempty value[i].id in the JSON.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(result,'value[i].displayName') <> 1) or (CkJsonObject_StringOfEquals(result,'value[i].displayName','',True) = True)) then
begin
Memo1.Lines.Add('Expected a nonempty value[i].displayName in the JSON.');
Exit;
end;
folderId := CkJsonObject__stringOf(result,'value[i].id');
CkStringBuilder_SetString(segment,CkJsonObject__stringOf(result,'value[i].displayName'));
// Escape separators in display names to make the human-readable path unambiguous.
replaceCount := CkStringBuilder_Replace(segment,'%','%25');
replaceCount := CkStringBuilder_Replace(segment,'/','%2F');
CkStringBuilder_SetString(fullPath,parentPath);
CkStringBuilder_Append(fullPath,'/');
CkStringBuilder_Append(fullPath,CkStringBuilder__getAsString(segment));
folderPath := CkStringBuilder__getAsString(fullPath);
if (CkHashtable_Contains(folderMap,folderPath) = True) then
begin
Memo1.Lines.Add('Duplicate folder path; cannot safely overwrite the map.');
Exit;
end;
success := CkHashtable_AddStr(folderMap,folderPath,folderId);
if (success <> True) then
begin
Memo1.Lines.Add('Could not add the folder to the map.');
Exit;
end;
Memo1.Lines.Add(folderPath + ' -> ' + folderId);
if (CkJsonObject_IntOf(result,'value[i].childFolderCount') > 0) then
begin
CkStringBuilder_SetString(childUrl,'https://graph.microsoft.com/v1.0/me/mailFolders/');
CkStringBuilder_Append(childUrl,CkHttp__urlEncode(http,folderId));
CkStringBuilder_Append(childUrl,'/childFolders?includeHiddenFolders=true&$select=id,displayName,childFolderCount&$top=50');
CkStringArray_Append(urls,CkStringBuilder__getAsString(childUrl));
CkStringArray_Append(paths,folderPath);
end;
i := i + 1;
end;
// A quoted JSON path treats the period in @odata.nextLink literally.
nextType := CkJsonObject_JsonTypeOf(result,'"@odata.nextLink"');
if ((nextType = -1) or (nextType = 6)) then
begin
url := '';
end
else
begin
if ((nextType <> 1) or (CkJsonObject_StringOfEquals(result,'"@odata.nextLink"','',True) = True)) then
begin
Memo1.Lines.Add('Invalid continuation link; cannot establish completeness.');
Exit;
end;
url := CkJsonObject__stringOf(result,'"@odata.nextLink"');
end;
if (url <> '') then
begin
CkStringArray_Append(urls,url);
CkStringArray_Append(paths,parentPath);
end;
queueIndex := queueIndex + 1;
end;
if (queueIndex < CkStringArray_getLength(urls)) then
begin
Memo1.Lines.Add('Stopped at the 1000-request demonstration limit; no partial map saved.');
Exit;
end;
fac := CkFileAccess_Create();
success := CkFileAccess_DirEnsureExists(fac,'qa_data/outlook');
if (success <> True) then
begin
Memo1.Lines.Add('Could not create the private output directory.');
Exit;
end;
mapXml := CkStringBuilder_Create();
success := CkHashtable_ToXmlSb(folderMap,mapXml);
if (success <> True) then
begin
Memo1.Lines.Add('Could not serialize the folder map.');
Exit;
end;
success := CkStringBuilder_WriteFile(mapXml,'qa_data/outlook/folderMap.xml','utf-8',False);
if (success <> True) then
begin
Memo1.Lines.Add('Could not save the folder map.');
Exit;
end;
Memo1.Lines.Add('Folder map saved after completing the traversal.');
CkJsonObject_Dispose(token);
CkHttp_Dispose(http);
CkHttpResponse_Dispose(resp);
CkJsonObject_Dispose(result);
CkStringArray_Dispose(urls);
CkStringArray_Dispose(paths);
CkStringArray_Dispose(seenLinks);
CkStringBuilder_Dispose(nextLink);
CkStringBuilder_Dispose(segment);
CkStringBuilder_Dispose(fullPath);
CkStringBuilder_Dispose(childUrl);
CkHashtable_Dispose(folderMap);
CkFileAccess_Dispose(fac);
CkStringBuilder_Dispose(mapXml);