• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
OpenTechTips

OpenTechTips

Comprehensive IT Guides for Pros and Enthusiasts

MENUMENU
  • HOME
  • ALL TOPICS
    • Exchange
    • InfoSec
    • Linux
    • Networking
    • Scripting
      • PowerShell
    • SSL
    • Tools
    • Virtualization
    • Web
    • Windows
  • ABOUT
  • SUBSCRIBE
Home » Outlook Script to automate downloading attachments from incoming emails

Outlook Script to automate downloading attachments from incoming emails

July 1, 2020 - by Zsolt Agoston - last edited on July 10, 2020

Scenario: we have a dedicate mailbox that receives a regular report attached to an email every morning.

We want that attachment to be saved to a specific folder on a server, and move the message away from the Inbox to keep it clear.

1. Before We Begin

First, we create a new profile in Outlook called 'RegularReports'.

Outlook Script to automate downloading attachments from incoming emails

Then, we create a subfolder inside the Inbox called 'Old Reports', where the processed messages will be moved to.

Outlook Script to automate downloading attachments from incoming emails

2. The Script

The following PowerShell script will open the 'RegularReports' Outlook user profile, cycle through all the messages in the Inbox, and saves the *.7z attachments to C:\temp. When it finishes all messages are marked as read, and moved to ':\Inbox\Old Reports' folder in Outlook.

# Kill OUTLOOK.EXE if running in my context, otherwise the script won't run
Get-Process OUTLOOK -IncludeUserName | ?{$_.UserName -eq "ALWAYSHOTCAFE\admin"} | Stop-Process -Force

# Load Outlook
$o = New-Object -comobject outlook.application
$o.Session.Logon("RegularReports")
$n = $o.GetNamespace("MAPI")

# Pick Inbox
$Inbox =$n.GetDefaultFolder(6)

$SaveToFolder = "C:\temp"
$TargetFolder = $Inbox.Folders.Item("Old Reports")

$Inbox.Items | % {
               $msg = $_

               # Save attachment
               $msg.attachments | ?{$_.filename -like "*.7z"} | %{
                              $file = $_.filename
                              $_.saveasfile((Join-Path $SaveToFolder $file))
                              }
}

# Mark the messages as read, and move them to the 'Old Reports' folder.
# Because of the imperfection of the move() function, the loop doesn't end until the messages are moved
while ($Inbox.Items.Count -gt 0)
{
    foreach ($mail in $Inbox.Items)
               {
               $mail.UnRead = $false
               $mail.Move($TargetFolder)
               }
}

3. Allow the script access to Outlook

You might receive the following prompt, asking you to allow the script access to the mailbox.

Outlook Script to automate downloading attachments from incoming emails

If that happens, open Outlook, navigate to 'File/Options/Trust Center'. Locate the 'Programmatic Access' option and select 'Never warn me about suspicious activity'

Outlook Script to automate downloading attachments from incoming emails

4. Create a Scheduled Task

Next, we create a scheduled task on the computer to run the script every morning, even if the user is not logged in.

a. Open Task Scheduler, select 'Create Task'. Name will be 'Regular Report download every morning at 6am', make sure to select: run the task whether user is logged in or not.

Outlook Script to automate downloading attachments from incoming emails

b. Under the Triggers tab create a new trigger on a schedule, weekly every day at 6am.

Outlook Script to automate downloading attachments from incoming emails

c. Going forward on the Actions tab  configure to start powershell with the following arguments that specify the script to execute and the executionpolicy to make sure the script is not blocked

Program/script: 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
Arguments: '-ExecutionPolicy Bypass -File c:\scripts\RegularReports.ps1'

Outlook Script to automate downloading attachments from incoming emails

d. Next, under the Conditions tab we don't need to check anything

Outlook Script to automate downloading attachments from incoming emails

e. Finally, under the Settings area we allow the task to be run on demand, so we can test it anytime.

Outlook Script to automate downloading attachments from incoming emails

f. When running the task, don't worry if you see 0x41301 under run result, that means the script is still running. When it finishes the result will show 0x0

Outlook Script to automate downloading attachments from incoming emails

Reader Interactions

Comments

  1. Henrique da Costa says

    January 23, 2023 at 17:42

    Your script is sensational, but help me if you can. I receive several emails with XML and PDF files. I extract only the XMLs, but while the script is running and moving the messages to the Processed folder, other new incoming messages are not handled…

    Reply

Comments Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Tools

Secondary Sidebar

CONTENTS

  • 1. Before We Begin
  • 2. The Script
  • 3. Allow the script access to Outlook
  • 4. Create a Scheduled Task

  • Terms of Use
  • Disclaimer
  • Privacy Policy
Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
Manage options
{title} {title} {title}
Manage your privacy
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
Manage options
{title} {title} {title}