I have written a script that will cycle through my outlook inbox and save a specific file attachment that I receive daily.
I have two email addresses that I use with Outlook. Example: jdoe@company1.com and jdoe@company2.com
The problem I have run into is that my script will only go through and save the attachments from the Inbox of my first (default) email account (jdoe@company1.com), but I need the script to save the attachments from my other inbox belonging to (jdoe@company2.com).
I am a novice with PowerShell and I've not been able to find a solution online. I am using PowerShell 5.1 and below is my script.
$td = Get-Date -Format "yyyy-MM-dd"
$AttachFile = "File Name.xlsx"
$FileSavePath = "C:\Temp\Attached_File_" + $td + ".xlsx"
$outlook = new-object -com outlook.application
$mapi = $outlook.GetNamespace("MAPI")
$inbox = $mapi.GetDefaultFolder(6)
$emails = $inbox.Items
foreach ($email in $emails) {
if ($email.ReceivedTime.ToString("yyyy-MM-dd") = $td) {
$email.Attachments | Where-Object {$_.FileName -eq $AttachFile} | foreach {
$_.SaveAsFile($FileSavePath)
}}
}
Instead of using Namespace.GetDefaultFolder
(which only returns folders from your default store), use Namespace.Stores
collection, find the store you want (mapi.Stores.Item("jdoe@company2.com")
?), and use Store.GetDefaultFolder
.
Also, do not loop through all items in a folder - use Items.Restrict
or Items.Find/FindNext
with a query like "([ReceivedTime] < '11-15-2023') and ([ReceivedTime] > '11-14-2023')"