Download O365 email Attachments with Graph
30 January, 2024
In this video I demonstrate using Microsoft Graph API to Download Office 365 email attachments and overcome the 10 emails return limit. Spoiler: Not really a limit. I use PowerShell to invoke the API and go over the setup in the Azure Portal as well.
PowerShell Script:
$connectiondetails = @{ 'tenantid' = "6c04db9b-6dd4-4cb2-9761-XXXXXXXXXXXXX" 'Clientid' = "08a838d0-0gbc-4b82-93d9-XXXXXXXXXXXXX" 'Clientsecret' = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" | ConvertTo-SecureString -AsPlainText -Force } $token = Get-MsalToken @connectiondetails $accessToken = $token.AccessToken $url = "https://graph.microsoft.com/v1.0/me/mailFolders/'long ID string'/messages" $msgqry = $url + "?`$select=Id&`$filter=HasAttachments eq true" $msgs = Invoke-RestMethod $msgqry -Headers @{Authorization=("bearer {0}" -f $accessToken)} while ($msgs.value){ foreach ($m in $msgs.value){ $query = $url + "/" + $m.Id + "/attachments" $attachments = Invoke-RestMethod $query -Headers @{Authorization=("bearer {0}" -f $accessToken)} foreach ($attachment in $attachments.value){ $fname = "D:\downloads\attachments\" + $attachment.name $content = [System.Convert]::FromBase64String($attachment.ContentBytes) set-content -Path $fname -Value $content -Encoding Byte } } $msgqry = $msgs.'@odata.nextLink' if ($msgqry){ $msgs = Invoke-RestMethod $msgqry -Headers @{Authorization=("bearer {0}" -f $accessToken)} } else{ $msgs.value = '' } }
hello@aipsolutions.tech