Search code examples
powershellemailexchange-serverexchangewebservicesemail-attachments

PowerShell EWS API | How to download attachments?


In the code below, I am able to retrieve the subject of the email but unable to download the attachment. I am not even able to output the name of the attachment. The attachment is a WAV sound file.

Import-Module "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"

$folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId($v_FolderID)
$fiItems = $null
$iv = new-object Microsoft.Exchange.WebServices.Data.ItemView(1000)
$fiItems = $service.FindItems($folderid, $args[1], $iv)

foreach ($Item in $fiItems.Items[0])
{
    $v_Subject = $Item.Subject
    
    foreach($attachment in $Item.Attachments)
    {
    $attachment.Load()
    $attachmentname = $attachment.Name.ToString()
    $attachmentname
    $file = New-Object System.IO.FileStream("C:\", [System.IO.FileMode]::Create)
    $file.Write($attachment.Content, 0, $attachment.Content.Length)
    $file.Close()
    }

}
$iv.offset += $fiItems.Items.Count

Out-File -FilePath "C:\EWSSubject.txt" -InputObject $v_Subject```

Solution

  • You should first need to create a PropertySet object because the attachment information is not loaded automatically.

    ## Target Path Folder
    $TargetPath = "c:\temp\attachments"
    
    ## Create a PropertySet with the Attachments metadata
    $ItemPropetySet = [Microsoft.Exchange.WebServices.Data.PropertySet]::new(
    [Microsoft.Exchange.Webservices.Data.BasePropertySet]::IdOnly,
    [Microsoft.Exchange.WebServices.Data.ItemSchema]::Attachments,
    [Microsoft.Exchange.WebServices.Data.ItemSchema]::HasAttachments
    )
    

    Then:

    ## Iterate the items and find messages with attachments
    foreach ($item in $fiItems.Items)
    {
        ## Load the Message attachment metadata using the PropertySet Created
        $message = [Microsoft.Exchange.WebServices.Data.EmailMessage]::Bind(
        $service, $item.Id, $ItemPropetySet)
    
        if ($message.HasAttachments)
        {
            foreach ($attachment in $message.Attachments)
            {
                if ($attachment -is [Microsoft.Exchange.WebServices.Data.FileAttachment])
                {
                $FilePath = Join-Path $TargetPath $attachment.Name
                $attachment.Load($FilePath)
                }
            }
        }
    }