Home > database >  How to download first emails attachment using PowerShell?
How to download first emails attachment using PowerShell?

Time:12-12

I'm getting an automatic weekly email with an attachment, and with an outlook rule, it is being saved in a folder in my inbox. my goal is to create a PowerShell script that downloads the attachment from the email with the latest "ReceivedTime". I have managed to sort the Object in the folder by "ReceivedTime" and get the latest email in the list: "$emails[0]", I can see the name of the attachment but I cannot seem to find how to download the file itself. the error I get is as follows: "You cannot call a method on a null-valued expression."

my code look like this:

$outlook = New-Object -ComObject outlook.application
$mapi = $outlook.GetNamespace("MAPI");

#Get Folder path
$filePath = "C:\Temp\test"
$inbox = $mapi.GetDefaultFolder(6) 
$inbox.Folders | Select-Object FolderPath
$olFolderPath = "\\[email protected]\Inbox\compliance"

#Get Emails Items from folder
$targetFolder = $inbox.Folders | Where-Object { $_.FolderPath -eq $olFolderPath } 


#Sort Emails in folder by date
$emails = $targetFolder.Items | Sort-Object ReceivedTime -Descending

#download attachements
$emails[0].Attachments | Select-Object $_.saveasfile(($filePath))

I'm using this guide to download the attachment, but my use case is a bit different from what is described in the article: https://bronowski.it/blog/2020/09/saving-outlook-attachments-with-powershell/

Sorry if it is a very simple task, I'm new to PowerShell and just learning automation. Thank you very much :)

CodePudding user response:

First of all, I've noticed the following code:

#Sort Emails in folder by date
$emails = $targetFolder.Items | Sort-Object ReceivedTime -Descending

Instead, you need to use the Sort method of the Items class which sorts the collection of items by the specified property. The index for the collection is reset to 1 upon completion of this method. So, to get the first item use the 1 index instead of 0.

$emails[1].Attachments[1].SaveAsFile(($filePath))

Be aware, the Attachments object contains a set of Attachment objects that represent the attachments in an Outlook item. Use the Attachments property to return the Attachments collection for any Outlook item (except notes).

  • Related