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 Swift Downloads
func chilkatTest() {
var success: Bool = false
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false
var replaceCount: Int = 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.
let token = CkoJsonObject()!
token.strict = true
success = token.loadFile(path: "qa_data/tokens/microsoftGraph.json")
if success != true {
print("Could not read the private Graph token cache.")
return
}
if (token.jsonType(of: "access_token").intValue != 1) || (token.string(ofEquals: "access_token", value: "", caseSensitive: true) == true) {
print("Expected a nonempty access_token in the JSON.")
return
}
let http = CkoHttp()!
http.authToken = token.string(of: "access_token")
http.requireSslCertVerify = true
http.followRedirects = false
http.connectTimeout = 20
http.readTimeout = 60
http.setRequestHeader(name: "Accept", value: "application/json")
let resp = CkoHttpResponse()!
let result = CkoJsonObject()!
result.strict = true
// Queue each collection URL together with its parent path; no delimiter-packed records.
let urls = CkoStringArray()!
let paths = CkoStringArray()!
urls.append(str: "https://graph.microsoft.com/v1.0/me/mailFolders?includeHiddenFolders=true&$select=id,displayName,childFolderCount&$top=50")
paths.append(str: "")
let seenLinks = CkoStringArray()!
let nextLink = CkoStringBuilder()!
let segment = CkoStringBuilder()!
let fullPath = CkoStringBuilder()!
let childUrl = CkoStringBuilder()!
let folderMap = CkoHashtable()!
var queueIndex: Int = 0
while ((queueIndex < urls.length.intValue) && (queueIndex < 1000)) {
var url: String? = urls.getString(index: queueIndex)
var parentPath: String? = paths.getString(index: queueIndex)
nextLink.setString(value: url)
if nextLink.starts(with: "https://graph.microsoft.com/v1.0/", caseSensitive: true) != true {
print("Unexpected pagination host or API version; no request sent.")
return
}
if seenLinks.find(str: url, firstIndex: 0).intValue >= 0 {
print("Repeated pagination URL; stopping.")
return
}
seenLinks.append(str: url)
success = http.httpNoBody(verb: "GET", url: url, response: resp)
// A false result can still include an HTTP error response.
if (success != true) && (resp.statusCode.intValue == 0) {
print("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
return
}
if resp.statusCode.intValue != 200 {
print("Unexpected HTTP status: \(resp.statusCode.intValue)")
print("Request ID: \(resp.getHeaderField(fieldName: "request-id")!)")
if resp.statusCode.intValue == 429 {
print("Retry-After: \(resp.getHeaderField(fieldName: "Retry-After")!)")
}
if resp.statusCode.intValue == 401 {
print("Refresh the Graph access token or authorize again.")
}
return
}
success = result.load(json: resp.bodyStr)
if success != true {
print("Expected a well-formed JSON response.")
return
}
if result.jsonType(of: "value").intValue != 4 {
print("Expected a value array.")
return
}
var i: Int = 0
while (i < result.size(ofArray: "value").intValue) {
result.i = i
if (result.jsonType(of: "value[i].id").intValue != 1) || (result.string(ofEquals: "value[i].id", value: "", caseSensitive: true) == true) {
print("Expected a nonempty value[i].id in the JSON.")
return
}
if (result.jsonType(of: "value[i].displayName").intValue != 1) || (result.string(ofEquals: "value[i].displayName", value: "", caseSensitive: true) == true) {
print("Expected a nonempty value[i].displayName in the JSON.")
return
}
var folderId: String? = result.string(of: "value[i].id")
segment.setString(value: result.string(of: "value[i].displayName"))
// Escape separators in display names to make the human-readable path unambiguous.
replaceCount = segment.replace(value: "%", replacement: "%25").intValue
replaceCount = segment.replace(value: "/", replacement: "%2F").intValue
fullPath.setString(value: parentPath)
fullPath.append(value: "/")
fullPath.append(value: segment.getAsString())
var folderPath: String? = fullPath.getAsString()
if folderMap.contains(key: folderPath) == true {
print("Duplicate folder path; cannot safely overwrite the map.")
return
}
success = folderMap.addStr(key: folderPath, value: folderId)
if success != true {
print("Could not add the folder to the map.")
return
}
print("\(folderPath!) -> \(folderId!)")
if result.int(of: "value[i].childFolderCount").intValue > 0 {
childUrl.setString(value: "https://graph.microsoft.com/v1.0/me/mailFolders/")
childUrl.append(value: http.urlEncode(str: folderId))
childUrl.append(value: "/childFolders?includeHiddenFolders=true&$select=id,displayName,childFolderCount&$top=50")
urls.append(str: childUrl.getAsString())
paths.append(str: folderPath)
}
i = i + 1
}
// A quoted JSON path treats the period in @odata.nextLink literally.
var nextType: Int = result.jsonType(of: "\"@odata.nextLink\"").intValue
if (nextType == -1) || (nextType == 6) {
url = ""
}
else {
if (nextType != 1) || (result.string(ofEquals: "\"@odata.nextLink\"", value: "", caseSensitive: true) == true) {
print("Invalid continuation link; cannot establish completeness.")
return
}
url = result.string(of: "\"@odata.nextLink\"")
}
if url != "" {
urls.append(str: url)
paths.append(str: parentPath)
}
queueIndex = queueIndex + 1
}
if queueIndex < urls.length.intValue {
print("Stopped at the 1000-request demonstration limit; no partial map saved.")
return
}
let fac = CkoFileAccess()!
success = fac.dirEnsureExists(dirPath: "qa_data/outlook")
if success != true {
print("Could not create the private output directory.")
return
}
let mapXml = CkoStringBuilder()!
success = folderMap.toXmlSb(sbXml: mapXml)
if success != true {
print("Could not serialize the folder map.")
return
}
success = mapXml.writeFile(path: "qa_data/outlook/folderMap.xml", charset: "utf-8", emitBom: false)
if success != true {
print("Could not save the folder map.")
return
}
print("Folder map saved after completing the traversal.")
}