Outlook Mail: Download File Attachments
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 each fileAttachment through its /$value endpoint, including inline files. Item and reference attachments are explicitly skipped. /$value can export item attachments as MIME/vCard/iCalendar in separate code, but is unsupported for reference attachments (405). A cloud reference needs its own authorized retrieval flow.
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 Lua Downloads
local chilkat = require("chilkat")
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local 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.
local token = chilkat.JsonObject.new()
token.strict = true
success = token:load_file("qa_data/tokens/microsoftGraph.json")
if not success then
print("Could not read the private Graph token cache.")
return
end
if (token:json_type_of("access_token") ~= 1) or (token:string_of_equals("access_token", "", true)) then
print("Expected a nonempty access_token in the JSON.")
return
end
local http = chilkat.Http.new()
http.auth_token = token:string_of("access_token")
http.require_ssl_cert_verify = true
http.follow_redirects = false
http.connect_timeout = 20
http.read_timeout = 60
http:set_request_header("Accept", "application/json")
local resp = chilkat.HttpResponse.new()
local result = chilkat.JsonObject.new()
result.strict = true
http:set_request_header("Prefer", "IdType=\"ImmutableId\"")
local fac = chilkat.FileAccess.new()
success = fac:dir_ensure_exists("qa_output/outlook")
if not success then
print("Could not create the output directory.")
return
end
local uuid = chilkat.Crypt2.new()
local data = chilkat.BinData.new()
local attachmentResp = chilkat.HttpResponse.new()
local attachment = chilkat.JsonObject.new()
attachment.strict = true
local downloadUrl = chilkat.StringBuilder.new()
local savePath = chilkat.StringBuilder.new()
local contentType = chilkat.StringBuilder.new()
local manifest = chilkat.JsonObject.new()
local savedCount = 0
local messageId = "YOUR_MESSAGE_ID"
local endpoint = chilkat.StringBuilder.new()
endpoint:append("https://graph.microsoft.com/v1.0/me/messages/")
endpoint:append(http:url_encode(messageId))
endpoint:append("/attachments?$select=id,name,contentType,size,isInline&$top=50")
local url = endpoint:get_as_string()
local nextLink = chilkat.StringBuilder.new()
local seenLinks = chilkat.Hashtable.new()
local pageCount = 0
while (url ~= "") and (pageCount < 100) do
nextLink:set_string(url)
if not nextLink:starts_with("https://graph.microsoft.com/v1.0/", true) then
print("Unexpected pagination host or API version; no request sent.")
return
end
if seenLinks:contains(url) then
print("Repeated pagination URL; stopping.")
return
end
seenLinks:add_int(url, 1)
success = http:http_no_body("GET", url, resp)
-- A false result can still include an HTTP error response.
if (not success) and (resp.status_code == 0) then
print("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
return
end
if resp.status_code ~= 200 then
print("Unexpected HTTP status: " .. resp.status_code)
print("Request ID: " .. resp:get_header_field("request-id"))
if resp.status_code == 429 then
print("Retry-After: " .. resp:get_header_field("Retry-After"))
end
if resp.status_code == 401 then
print("Refresh the Graph access token or authorize again.")
end
return
end
success = result:load(resp.body_str)
if not success then
print("Expected a well-formed JSON response.")
return
end
if result:json_type_of("value") ~= 4 then
print("Expected a value array.")
return
end
local i = 0
while i < result:size_of_array("value") do
result.i = i
if (result:json_type_of("value[i].id") ~= 1) or (result:string_of_equals("value[i].id", "", true)) then
print("Expected a nonempty value[i].id in the JSON.")
return
end
local attachmentType = result:string_of("value[i].\"@odata.type\"")
local wanted = result:string_of_equals("value[i].\"@odata.type\"", "#microsoft.graph.fileAttachment", true)
if wanted then
local attachmentId = result:string_of("value[i].id")
downloadUrl:set_string("https://graph.microsoft.com/v1.0/me/messages/")
downloadUrl:append(http:url_encode(messageId))
downloadUrl:append("/attachments/")
downloadUrl:append(http:url_encode(attachmentId))
downloadUrl:append("/$value")
http:set_request_header("Accept", "*/*")
success = http:http_no_body("GET", downloadUrl:get_as_string(), attachmentResp)
-- A false result can still include an HTTP error response.
if (not success) and (attachmentResp.status_code == 0) then
print("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
return
end
if attachmentResp.status_code ~= 200 then
print("Unexpected HTTP status: " .. attachmentResp.status_code)
print("Request ID: " .. attachmentResp:get_header_field("request-id"))
if attachmentResp.status_code == 429 then
print("Retry-After: " .. attachmentResp:get_header_field("Retry-After"))
end
if attachmentResp.status_code == 401 then
print("Refresh the Graph access token or authorize again.")
end
return
end
http:set_request_header("Accept", "application/json")
data:clear()
success = attachmentResp:get_body_bd(data)
if not success then
print("Could not read the binary attachment.")
return
end
-- Server-provided names are metadata, never local filesystem paths.
-- Choose a fresh generated filename; keep the original name in a manifest.
savePath:set_string("qa_output/outlook/")
local localId = uuid:generate_uuid()
if not uuid.last_method_success then
print("Could not generate a local filename.")
return
end
savePath:append(localId)
savePath:append(".bin")
if fac:file_exists(savePath:get_as_string()) then
print("Output file already exists; refusing to overwrite it.")
return
end
success = data:write_file(savePath:get_as_string())
if not success then
print("Could not save attachment bytes.")
return
end
manifest.i = savedCount
manifest:update_string("files[i].attachmentId", attachmentId)
manifest:update_string("files[i].originalName", result:string_of("value[i].name"))
manifest:update_string("files[i].contentType", result:string_of("value[i].contentType"))
manifest:update_string("files[i].localFile", savePath:get_as_string())
savedCount = savedCount + 1
print("Saved: " .. savePath:get_as_string())
else
print("Skipped attachment type/inline selection: " .. attachmentType)
end
i = i + 1
end
pageCount = pageCount + 1
-- A quoted JSON path treats the period in @odata.nextLink literally.
local nextType = result:json_type_of("\"@odata.nextLink\"")
if (nextType == (-1)) or (nextType == 6) then
url = ""
else
if (nextType ~= 1) or (result:string_of_equals("\"@odata.nextLink\"", "", true)) then
print("Invalid continuation link; cannot establish completeness.")
return
end
url = result:string_of("\"@odata.nextLink\"")
end
end
if url ~= "" then
print("Stopped at the example's 100-page limit; save the continuation privately to resume.")
return
end
print("Completed pages: " .. pageCount)
savePath:set_string("qa_output/outlook/")
local manifestId = uuid:generate_uuid()
if not uuid.last_method_success then
print("Could not generate the manifest filename.")
return
end
savePath:append(manifestId)
savePath:append(".json")
success = manifest:write_file(savePath:get_as_string())
if not success then
print("Files saved, but manifest could not be saved.")
return
end
print("Saved file count: " .. savedCount)
print("Manifest: " .. savePath:get_as_string())