**This will only work on Windows PC Devices and Microsoft Outlook email client**
Use pywin32 to save and file any Outlook email attachment
Jump to Full Code↓
Do you receive a weekly report via Outlook that you need to file manually each week? Or maybe have a short email retention policy (and a short term memory) that makes you constantly lose files? Sure, doing this manually isn’t hard but learning how to automate short tasks can save you tons of time over the course of your career.
This article will teach you how to use Python to automate downloading any Outlook attachments and save them in a designated custom file. You will need python installed on your Windows PC computer (this will NOT work on a Mac). We recommend running this in a Jupyter Notebook, so you can easily run each code block, section by section.
First, import the win32com.client and os packages.
import win32com.client
import os
#having issues installing win32com? try the below (without the hashtag)
#pip install pypiwin32
#pip install pywin32
#python -m pip install pypiwin32
Then, Copy & Paste the below save_outook_attachments Function into a Code Editor
The below Python function was written by our team to ensure you have everything you need to automate downloading Outlook attachments. Try running the below function to make sure it works without an errors. You can copy and paste the below into whatever editor you use.
def save_outlook_attachments(folder_name,subject_line,save_location):
outlook_application = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
outlook_mailbox =outlook_application.Folders.Item(1)
#this is your default mailbox. if you have multiple mailboxes in outlook try increasing this number (2,3,4 etc.)
#Finds the correct Outlook Folder by searching for a folder that is equal to folder_name
for folder in outlook_mailbox.Folders:
if folder.Name == folder_name:
found_folder = folder
print('Folder Searched:' + found_folder.Name)
#Sorts all emails in folder by date (descending)
folder_emails = found_folder.Items
folder_emails.Sort("[ReceivedTime]", True)
#Looks for correct email by searching for an email containing subject_line
for email in folder_emails:
if subject_line in email.Subject: #If exact subject_line match is needed, switch "in" to "=="
print('Found email with subject '+ email.Subject + ' sent on ' + email.SentOn.strftime('%m-%d-%y'))
found_email = email
break
#Gets email attachment from email and saves to file location
num_email_attachments = len([x for x in found_email.attachments])+1
for attachment_num in range(1, num_email_attachments):
attachment = found_email.attachments.Item(attachment_num)
attachment_name = str(attachment)
print('Attachment Number ' + str(attachment_num) +' - File Name : '+attachment_name)
save_file_path = os.path.join (save_location,attachment_name)
attachment.SaveAsFile(save_file_path)
print('Attachment ' + str(attachment) +" saved to " + save_file_path)
Next, define your email criteria
In order to automate downloading Outlook attachments with Python, we need to provide the program information about what emails we are looking for. This includes
- folder_name = which folder the email lives in (Inbox? or a Custom Outlook Folder?)
- subject_line = a phrase that will help us identify the correct email via subject line (i.e find the last email that contains “Weekly Report”)
- save_location = this is the file path where you want the email attachment to automatically save to
folder_name = 'Inbox' subject_line = 'Weekly Report' #case senstive, must contain phrase save_location = r'C:\Users\YOUR_USER_NAME_HERE\Documents\Weekly Reports'
#the r before the file location is not a typo! It helps format the code correctly.
Finally, you’re ready to run!
Copy & paste the below code under your defined variables and hit Run! You should then be able to automatically download any Outlook attachment automatically with Python and save it to a designated file location. This code will produce output letting you know if you’re successful or not. However, you can always check your specified save location yourself, to make sure the attachments saved in the correct spot.
save_outlook_attachments(folder_name,subject_line,save_location)
Output:
>Folder Searched:Inbox
>Found email with subject Weekly Report sent on 11-12-22
>Attachment Number 1 - File Name : Weekly Report.csv
>Attachment Weekly Report.csv saved to C:\Users\YOUR_USERNAME_HERE\Documents\Weekly Report.csv
How to Automatically Download Outlook Attachments – Python Full Code
import win32com.client import os #Define Save Outlook Attachments Function def save_outlook_attachments(folder_name,subject_line,save_location): outlook_application = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") outlook_mailbox =outlook_application.Folders.Item(1) #this is your default mailbox. if you have multiple mailboxes in outlook try increasing this number (2,3,4 etc.) #Finds the correct Outlook Folder by searching for a folder that is equal to folder_name for folder in outlook_mailbox.Folders: if folder.Name == folder_name: found_folder = folder print('Folder Searched:' + found_folder.Name) #Sorts all emails in folder by date (descending) folder_emails = found_folder.Items folder_emails.Sort("[ReceivedTime]", True) #Looks for correct email by searching for an email containing subject_line for email in folder_emails: if subject_line in email.Subject: #If exact subject_line match is needed, switch "in" to "==" print('Found email with subject '+ email.Subject + ' sent on ' + email.SentOn.strftime('%m-%d-%y')) found_email = email break #Gets email attachment from email and saves to file location num_email_attachments = len([x for x in found_email.attachments])+1 for attachment_num in range(1, num_email_attachments): attachment = found_email.attachments.Item(attachment_num) attachment_name = str(attachment) print('Attachment Number ' + str(attachment_num) +' - File Name : '+attachment_name) save_file_path = os.path.join (save_location,attachment_name) attachment.SaveAsFile(save_file_path) print('Attachment ' + str(attachment) +" saved to " + save_file_path) #Define Variables folder_name = 'Inbox' subject_line = 'Weekly Report' #case senstive, must contain phrase save_location = r'C:\Users\YOUR_USER_NAME_HERE\Documents\Weekly Reports' #the r before the file location is not a typo! It helps format the code correctly. #Run Function save_outlook_attachments(folder_name,subject_line,save_location)
Leave a Reply