Outlook Mail: Download Inline Images and Record Content IDs
See more Outlook Examples
Attachments can be fileAttachment (binary file), itemAttachment (attached message/contact/event), or referenceAttachment (cloud-file link). Do not assume every attachment contains contentBytes. Inline images are file attachments with isInline=true and a contentId corresponding to an HTML cid: reference. hasAttachments on the parent message excludes inline-only images.
Download only inline image file attachments, decode their base64 content, and preserve the contentId-to-local-file mapping in a JSON manifest. This uses Graph attachment JSON, not a MIME parser. CID images are included; externally hosted image URLs are not fetched. Do not display untrusted message HTML without sanitizing it. The contentType is sender-supplied metadata, not a safety guarantee.
Use generated .bin filenames and a manifest to preserve original names without allowing path traversal or collisions from sender-controlled filenames. Inspect files before opening them. HTTP errors are checked before saving bytes. Already saved files remain if a later request fails; this example is not a transactional export and buffers each download in memory. A production exporter should checkpoint per attachment and use atomic/exclusive writes and an account-specific directory.
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.Read.
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\"")
let fac = CkoFileAccess()!
success = fac.dirEnsureExists(dirPath: "qa_output/outlook")
if success != true {
print("Could not create the output directory.")
return
}
let uuid = CkoCrypt2()!
let data = CkoBinData()!
let attachmentResp = CkoHttpResponse()!
let attachment = CkoJsonObject()!
attachment.strict = true
let downloadUrl = CkoStringBuilder()!
let savePath = CkoStringBuilder()!
let contentType = CkoStringBuilder()!
let manifest = CkoJsonObject()!
var savedCount: Int = 0
var messageId: String? = "YOUR_MESSAGE_ID"
let endpoint = CkoStringBuilder()!
endpoint.append(value: "https://graph.microsoft.com/v1.0/me/messages/")
endpoint.append(value: http.urlEncode(str: messageId))
endpoint.append(value: "/attachments?$select=id,name,contentType,size,isInline&$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 attachmentType: String? = result.string(of: "value[i].\"@odata.type\"")
var wanted: Bool = result.string(ofEquals: "value[i].\"@odata.type\"", value: "#microsoft.graph.fileAttachment", caseSensitive: true)
contentType.setString(value: result.string(of: "value[i].contentType"))
wanted = wanted && result.bool(of: "value[i].isInline") && contentType.starts(with: "image/", caseSensitive: false)
if wanted == true {
var attachmentId: String? = result.string(of: "value[i].id")
downloadUrl.setString(value: "https://graph.microsoft.com/v1.0/me/messages/")
downloadUrl.append(value: http.urlEncode(str: messageId))
downloadUrl.append(value: "/attachments/")
downloadUrl.append(value: http.urlEncode(str: attachmentId))
success = http.httpNoBody(verb: "GET", url: downloadUrl.getAsString(), response: attachmentResp)
// A false result can still include an HTTP error response.
if (success != true) && (attachmentResp.statusCode.intValue == 0) {
print("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
return
}
if attachmentResp.statusCode.intValue != 200 {
print("Unexpected HTTP status: \(attachmentResp.statusCode.intValue)")
print("Request ID: \(attachmentResp.getHeaderField(fieldName: "request-id")!)")
if attachmentResp.statusCode.intValue == 429 {
print("Retry-After: \(attachmentResp.getHeaderField(fieldName: "Retry-After")!)")
}
if attachmentResp.statusCode.intValue == 401 {
print("Refresh the Graph access token or authorize again.")
}
return
}
success = attachment.load(json: attachmentResp.bodyStr)
if success != true {
print("Expected a well-formed JSON response.")
return
}
if (attachment.jsonType(of: "contentId").intValue != 1) || (attachment.string(ofEquals: "contentId", value: "", caseSensitive: true) == true) {
print("Expected a nonempty contentId in the JSON.")
return
}
if attachment.jsonType(of: "contentBytes").intValue != 1 {
print("Expected base64 file content.")
return
}
data.clear()
success = data.appendEncoded(encData: attachment.string(of: "contentBytes"), encoding: "base64")
if success != true {
print("Could not decode the inline image.")
return
}
// Server-provided names are metadata, never local filesystem paths.
// Choose a fresh generated filename; keep the original name in a manifest.
savePath.setString(value: "qa_output/outlook/")
var localId: String? = uuid.generateUuid()
if uuid.lastMethodSuccess != true {
print("Could not generate a local filename.")
return
}
savePath.append(value: localId)
savePath.append(value: ".bin")
if fac.fileExists(path: savePath.getAsString()) == true {
print("Output file already exists; refusing to overwrite it.")
return
}
success = data.writeFile(path: savePath.getAsString())
if success != true {
print("Could not save attachment bytes.")
return
}
manifest.i = savedCount
manifest.updateString(jsonPath: "files[i].attachmentId", value: attachmentId)
manifest.updateString(jsonPath: "files[i].originalName", value: result.string(of: "value[i].name"))
manifest.updateString(jsonPath: "files[i].contentType", value: result.string(of: "value[i].contentType"))
manifest.updateString(jsonPath: "files[i].localFile", value: savePath.getAsString())
manifest.updateString(jsonPath: "files[i].contentId", value: attachment.string(of: "contentId"))
print("Content-ID: \(attachment.string(of: "contentId")!)")
savedCount = savedCount + 1
print("Saved: \(savePath.getAsString()!)")
}
else {
print("Skipped attachment type/inline selection: \(attachmentType!)")
}
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)")
savePath.setString(value: "qa_output/outlook/")
var manifestId: String? = uuid.generateUuid()
if uuid.lastMethodSuccess != true {
print("Could not generate the manifest filename.")
return
}
savePath.append(value: manifestId)
savePath.append(value: ".json")
success = manifest.writeFile(path: savePath.getAsString())
if success != true {
print("Files saved, but manifest could not be saved.")
return
}
print("Saved file count: \(savedCount)")
print("Manifest: \(savePath.getAsString()!)")
}