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 AutoIt Downloads
Local $bSuccess = False
; Assumes Chilkat is unlocked. See Global Unlock Sample.
$bSuccess = 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.
$oToken = ObjCreate("Chilkat.JsonObject")
$oToken.Strict = True
$bSuccess = $oToken.LoadFile("qa_data/tokens/microsoftGraph.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not read the private Graph token cache." & @CRLF)
Exit
EndIf
If (($oToken.JsonTypeOf("access_token") <> 1) Or ($oToken.StringOfEquals("access_token","",True) = True)) Then
ConsoleWrite("Expected a nonempty access_token in the JSON." & @CRLF)
Exit
EndIf
$oHttp = ObjCreate("Chilkat.Http")
$oHttp.AuthToken = $oToken.StringOf("access_token")
$oHttp.RequireSslCertVerify = True
$oHttp.FollowRedirects = False
$oHttp.ConnectTimeout = 20
$oHttp.ReadTimeout = 60
$oHttp.SetRequestHeader "Accept","application/json"
$oResp = ObjCreate("Chilkat.HttpResponse")
$oResult = ObjCreate("Chilkat.JsonObject")
$oResult.Strict = True
$oHttp.SetRequestHeader "Prefer","IdType=""ImmutableId"""
$oFac = ObjCreate("Chilkat.FileAccess")
$bSuccess = $oFac.DirEnsureExists("qa_output/outlook")
If ($bSuccess <> True) Then
ConsoleWrite("Could not create the output directory." & @CRLF)
Exit
EndIf
$oUuid = ObjCreate("Chilkat.Crypt2")
$oData = ObjCreate("Chilkat.BinData")
$oAttachmentResp = ObjCreate("Chilkat.HttpResponse")
$oAttachment = ObjCreate("Chilkat.JsonObject")
$oAttachment.Strict = True
$oDownloadUrl = ObjCreate("Chilkat.StringBuilder")
$oSavePath = ObjCreate("Chilkat.StringBuilder")
$oContentType = ObjCreate("Chilkat.StringBuilder")
$oManifest = ObjCreate("Chilkat.JsonObject")
Local $iSavedCount = 0
Local $sMessageId = "YOUR_MESSAGE_ID"
$oEndpoint = ObjCreate("Chilkat.StringBuilder")
$oEndpoint.Append("https://graph.microsoft.com/v1.0/me/messages/")
$oEndpoint.Append($oHttp.UrlEncode($sMessageId))
$oEndpoint.Append("/attachments?$select=id,name,contentType,size,isInline&$top=50")
Local $sUrl = $oEndpoint.GetAsString()
$oNextLink = ObjCreate("Chilkat.StringBuilder")
$oSeenLinks = ObjCreate("Chilkat.Hashtable")
Local $iPageCount = 0
While (($sUrl <> "") And ($iPageCount < 100))
$oNextLink.SetString($sUrl)
If ($oNextLink.StartsWith("https://graph.microsoft.com/v1.0/",True) <> True) Then
ConsoleWrite("Unexpected pagination host or API version; no request sent." & @CRLF)
Exit
EndIf
If ($oSeenLinks.Contains($sUrl) = True) Then
ConsoleWrite("Repeated pagination URL; stopping." & @CRLF)
Exit
EndIf
$oSeenLinks.AddInt($sUrl,1)
$bSuccess = $oHttp.HttpNoBody("GET",$sUrl,$oResp)
; A false result can still include an HTTP error response.
If (($bSuccess <> True) And ($oResp.StatusCode = 0)) Then
ConsoleWrite("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying." & @CRLF)
Exit
EndIf
If ($oResp.StatusCode <> 200) Then
ConsoleWrite("Unexpected HTTP status: " & $oResp.StatusCode & @CRLF)
ConsoleWrite("Request ID: " & $oResp.GetHeaderField("request-id") & @CRLF)
If ($oResp.StatusCode = 429) Then
ConsoleWrite("Retry-After: " & $oResp.GetHeaderField("Retry-After") & @CRLF)
EndIf
If ($oResp.StatusCode = 401) Then
ConsoleWrite("Refresh the Graph access token or authorize again." & @CRLF)
EndIf
Exit
EndIf
$bSuccess = $oResult.Load($oResp.BodyStr)
If ($bSuccess <> True) Then
ConsoleWrite("Expected a well-formed JSON response." & @CRLF)
Exit
EndIf
If ($oResult.JsonTypeOf("value") <> 4) Then
ConsoleWrite("Expected a value array." & @CRLF)
Exit
EndIf
Local $i = 0
While ($i < $oResult.SizeOfArray("value"))
$oResult.I = $i
If (($oResult.JsonTypeOf("value[i].id") <> 1) Or ($oResult.StringOfEquals("value[i].id","",True) = True)) Then
ConsoleWrite("Expected a nonempty value[i].id in the JSON." & @CRLF)
Exit
EndIf
Local $sAttachmentType = $oResult.StringOf("value[i].""@odata.type""")
Local $bWanted = $oResult.StringOfEquals("value[i].""@odata.type""","#microsoft.graph.fileAttachment",True)
$oContentType.SetString($oResult.StringOf("value[i].contentType"))
$bWanted = $bWanted And $oResult.BoolOf("value[i].isInline") And $oContentType.StartsWith("image/",False)
If ($bWanted = True) Then
Local $sAttachmentId = $oResult.StringOf("value[i].id")
$oDownloadUrl.SetString("https://graph.microsoft.com/v1.0/me/messages/")
$oDownloadUrl.Append($oHttp.UrlEncode($sMessageId))
$oDownloadUrl.Append("/attachments/")
$oDownloadUrl.Append($oHttp.UrlEncode($sAttachmentId))
$bSuccess = $oHttp.HttpNoBody("GET",$oDownloadUrl.GetAsString(),$oAttachmentResp)
; A false result can still include an HTTP error response.
If (($bSuccess <> True) And ($oAttachmentResp.StatusCode = 0)) Then
ConsoleWrite("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying." & @CRLF)
Exit
EndIf
If ($oAttachmentResp.StatusCode <> 200) Then
ConsoleWrite("Unexpected HTTP status: " & $oAttachmentResp.StatusCode & @CRLF)
ConsoleWrite("Request ID: " & $oAttachmentResp.GetHeaderField("request-id") & @CRLF)
If ($oAttachmentResp.StatusCode = 429) Then
ConsoleWrite("Retry-After: " & $oAttachmentResp.GetHeaderField("Retry-After") & @CRLF)
EndIf
If ($oAttachmentResp.StatusCode = 401) Then
ConsoleWrite("Refresh the Graph access token or authorize again." & @CRLF)
EndIf
Exit
EndIf
$bSuccess = $oAttachment.Load($oAttachmentResp.BodyStr)
If ($bSuccess <> True) Then
ConsoleWrite("Expected a well-formed JSON response." & @CRLF)
Exit
EndIf
If (($oAttachment.JsonTypeOf("contentId") <> 1) Or ($oAttachment.StringOfEquals("contentId","",True) = True)) Then
ConsoleWrite("Expected a nonempty contentId in the JSON." & @CRLF)
Exit
EndIf
If ($oAttachment.JsonTypeOf("contentBytes") <> 1) Then
ConsoleWrite("Expected base64 file content." & @CRLF)
Exit
EndIf
$oData.Clear()
$bSuccess = $oData.AppendEncoded($oAttachment.StringOf("contentBytes"),"base64")
If ($bSuccess <> True) Then
ConsoleWrite("Could not decode the inline image." & @CRLF)
Exit
EndIf
; Server-provided names are metadata, never local filesystem paths.
; Choose a fresh generated filename; keep the original name in a manifest.
$oSavePath.SetString("qa_output/outlook/")
Local $sLocalId = $oUuid.GenerateUuid()
If ($oUuid.LastMethodSuccess <> True) Then
ConsoleWrite("Could not generate a local filename." & @CRLF)
Exit
EndIf
$oSavePath.Append($sLocalId)
$oSavePath.Append(".bin")
If ($oFac.FileExists($oSavePath.GetAsString()) = True) Then
ConsoleWrite("Output file already exists; refusing to overwrite it." & @CRLF)
Exit
EndIf
$bSuccess = $oData.WriteFile($oSavePath.GetAsString())
If ($bSuccess <> True) Then
ConsoleWrite("Could not save attachment bytes." & @CRLF)
Exit
EndIf
$oManifest.I = $iSavedCount
$oManifest.UpdateString("files[i].attachmentId",$sAttachmentId)
$oManifest.UpdateString("files[i].originalName",$oResult.StringOf("value[i].name"))
$oManifest.UpdateString("files[i].contentType",$oResult.StringOf("value[i].contentType"))
$oManifest.UpdateString("files[i].localFile",$oSavePath.GetAsString())
$oManifest.UpdateString("files[i].contentId",$oAttachment.StringOf("contentId"))
ConsoleWrite("Content-ID: " & $oAttachment.StringOf("contentId") & @CRLF)
$iSavedCount = $iSavedCount + 1
ConsoleWrite("Saved: " & $oSavePath.GetAsString() & @CRLF)
Else
ConsoleWrite("Skipped attachment type/inline selection: " & $sAttachmentType & @CRLF)
EndIf
$i = $i + 1
Wend
$iPageCount = $iPageCount + 1
; A quoted JSON path treats the period in @odata.nextLink literally.
Local $iNextType = $oResult.JsonTypeOf("""@odata.nextLink""")
If (($iNextType = -1) Or ($iNextType = 6)) Then
$sUrl = ""
Else
If (($iNextType <> 1) Or ($oResult.StringOfEquals("""@odata.nextLink""","",True) = True)) Then
ConsoleWrite("Invalid continuation link; cannot establish completeness." & @CRLF)
Exit
EndIf
$sUrl = $oResult.StringOf("""@odata.nextLink""")
EndIf
Wend
If ($sUrl <> "") Then
ConsoleWrite("Stopped at the example's 100-page limit; save the continuation privately to resume." & @CRLF)
Exit
EndIf
ConsoleWrite("Completed pages: " & $iPageCount & @CRLF)
$oSavePath.SetString("qa_output/outlook/")
Local $sManifestId = $oUuid.GenerateUuid()
If ($oUuid.LastMethodSuccess <> True) Then
ConsoleWrite("Could not generate the manifest filename." & @CRLF)
Exit
EndIf
$oSavePath.Append($sManifestId)
$oSavePath.Append(".json")
$bSuccess = $oManifest.WriteFile($oSavePath.GetAsString())
If ($bSuccess <> True) Then
ConsoleWrite("Files saved, but manifest could not be saved." & @CRLF)
Exit
EndIf
ConsoleWrite("Saved file count: " & $iSavedCount & @CRLF)
ConsoleWrite("Manifest: " & $oSavePath.GetAsString() & @CRLF)