Outlook Mail: Find Unread Messages in a Folder Subtree
See more Outlook Examples
Find unread messages in a selected folder and all descendants listed in a previously built folder map. Each folder has its own paginated request. Matching uses the exact path or path-plus-slash prefix, so /InboxOther is excluded. Immutable message IDs are deduplicated across results; concurrent changes can still prevent a perfectly consistent snapshot.
For the entire mailbox, use /me/messages?$filter=isRead eq false directly; no recursive traversal is needed. Traverse folders only when limiting the query to a particular subtree. A stale map can omit new folders, so refresh it as needed. Map paths are case-sensitive display paths, including the escaping convention documented by the map example.
Follows the complete @odata.nextLink, including empty pages with a continuation. The example checks the Graph host, rejects repeated links, and stops explicitly after 100 pages; this is a demonstration bound, not an API limit. Save the next URL privately to resume larger scans. $top controls page size, not the total result count.
IDs are opaque, case-sensitive strings, not numbers or Internet Message-ID headers. URL-encode each ID as a path segment. Message examples request Prefer: IdType="ImmutableId" consistently so moves within the same mailbox retain the ID. Retrieve IDs with that preference or deliberately convert older IDs; do not change their characters or assume an old default-format ID is immutable.
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
// 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
http.setRequestHeader(name: "Prefer", value: "IdType=\"ImmutableId\"")
// Build the map first: Create a Folder Path-to-ID Map.
// Use the actual localized/escaped path from that map.
var rootPath: String? = "/Inbox"
let map = CkoXml()!
success = map.loadFile(path: "qa_data/outlook/folderMap.xml")
if success != true {
print("Could not read the mailbox folder map.")
return
}
let prefix = CkoStringBuilder()!
prefix.append(value: rootPath)
prefix.append(value: "/")
let path = CkoStringBuilder()!
let endpoint = CkoStringBuilder()!
let seenMessages = CkoStringArray()!
var folderIndex: Int = 0
while (folderIndex < map.numChildren.intValue) {
map.i = folderIndex
var folderPath: String? = map.getChildContent(tagPath: "e[i]|k")
path.setString(value: folderPath)
// Include /Inbox and /Inbox/... but not /InboxOther.
if (folderPath == rootPath) || (path.starts(with: prefix.getAsString(), caseSensitive: true) == true) {
var folderId: String? = map.getChildContent(tagPath: "e[i]|v")
endpoint.setString(value: "https://graph.microsoft.com/v1.0/me/mailFolders/")
endpoint.append(value: http.urlEncode(str: folderId))
endpoint.append(value: "/messages?$filter=isRead%20eq%20false&$select=id,subject,from&$top=50")
var url: String? = endpoint.getAsString()
let nextLink = CkoStringBuilder()!
let seenLinks = CkoStringArray()!
var pageCount: Int = 0
while ((url != "") && (pageCount < 100)) {
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
}
var messageId: String? = result.string(of: "value[i].id")
// Concurrent moves/search folders can expose the same message more than once.
if seenMessages.find(str: messageId, firstIndex: 0).intValue < 0 {
seenMessages.append(str: messageId)
print("Folder path: \(folderPath!)")
print("Message ID: \(result.string(of: "value[i].id")!)")
print("Subject: \(result.string(of: "value[i].subject")!)")
print("From: \(result.string(of: "value[i].from.emailAddress.address")!)")
}
i = i + 1
}
pageCount = pageCount + 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 != "" {
print("Stopped at the example's 100-page limit; save the continuation privately to resume.")
return
}
print("Completed pages: \(pageCount)")
}
folderIndex = folderIndex + 1
}
print("Distinct matching message IDs: \(seenMessages.length.intValue)")
}