I found the below script from here:
Can I save an email attachment from Office 365 to a file share with PowerShell?
$ewsPath = "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
Add-Type -Path $ewsPath
$ews = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService
$cred = (Get-Credential).GetNetworkCredential()
$ews.Credentials = New-Object System.Net.NetworkCredential -ArgumentList $cred.UserName, $cred.Password, $cred.Domain
$ews.AutodiscoverUrl( "[email protected]", {$true} )
$results = $ews.FindItems(
"Inbox",
( New-Object Microsoft.Exchange.WebServices.Data.ItemView -ArgumentList 100 )
)
$MailItems = $results.Items | where hasattachments
foreach ($MailItem in $MailItems){
$MailItem.Load()
foreach($Attachment in $MailItem.Attachments){
$Attachment.Load()
$File = new-object System.IO.FileStream(("C:\AttachmentsDownloads\” + $attachment.Name.ToString()), [System.IO.FileMode]::Create)
$File.Write($attachment.Content, 0, $attachment.Content.Length)
$File.Close()
}
}
I can download the attachments, but when an email was attached as an attachment the download will fail. I have no idea what's the difference between a .msg file and a .pdf file when downloading it... and what I really need are the .msg attachments.
The error I am getting is below:
Exception calling "Write" with "3" argument(s): "Buffer cannot be null.
Parameter name: array"
At C:\DownloadAttachment.ps1:21 char:9
+ $File.Write($attachment.Content, 0, $attachment.Content.Lengt ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
Could you please help? Any help will be greatly appreciated!