Download email attachments - israel-dryer/Outlook-Python-Tutorial GitHub Wiki

You can use this script as a pattern to download attachments from email messages load

import win32com.client as client

# create instance of Outlook
outlook = client.Dispatch('Outlook.Application')

# get the inbox
namespace = outlook.GetNameSpace('MAPI')
inbox = namespace.GetDefaultFolder(6)

# the email I want to download a file from
target_subject = 'Testing attachment'

# get only mail items from the inbox (other items can exists and will return an error if you try get the subject line of a non-mail item)
mail_items = [item for item in inbox.Items if item.Class == 43]

# filter to the target email
filtered = [item for item in mail_items if item.Subject == target_subject]

# get the first item if it exists (assuming the there is only one item to get)
if len(filtered) != 0:
    target_email = filtered[0]
    
# get attachments
if target_email.Attachments.Count > 0:
    attachments = target_email.Attachments    
    
# save attachments to file
save_path = 'C:\\Users\\admin\\Documents\\GitHub\\Outlook-Email\\Attachments\\{}'

for file in attachments:
    file.SaveAsFile(save_path.format(file.FileName))