Search code examples
pythonoutlookemail-attachmentspywin32win32com

Python Saving Attachments from Outlook


I am trying to automate some python code that will automatically save some attachments from certain emails with a specific title.

Below is what I currently have:

import win32com.client as client

outlook = client.Dispatch('Outlook.Application')
namespace = outlook.GetNameSpace('MAPI')
inbox = namespace.GetDefaultFolder(6)
target_subject = 'Testing attachment'
mail_items = [item for item in inbox.Items if item.Class == 43]
filtered = [item for item in mail_items if item.Subject == target_subject]


if len(filtered) != 0:
    target_email = filtered[0]
    

if target_email.Attachments.Count > 0:
    attachments = target_email.Attachments    
    

save_path = 'C:'

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

However I seem to be getting an error with permissions?

com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', "Cannot save the attachment. You don't have appropriate permission to perform this operation.", None, 0, -2147024891), None)

Not sure how to work around this, I am the Admin etc.

I am also wondering what would be the changes required to actually deploy this online and have it running, i.e. I am not passing any credentials as it's local, if operating stand alone I would like it to access my inbox every 7 days or so and download this specific attachments from this specific email.

Any help will be greatly appreciated.

Thanks!


Solution

  • Choose another drive or folder, for example, My Documents doesn't require admin privileges for writing. Otherwise, you will have to run Outlook with admin privileges if you want to write anything to the system drive (C:).

    Also I've noticed the following lines of code:

    mail_items = [item for item in inbox.Items if item.Class == 43]
    filtered = [item for item in mail_items if item.Subject == target_subject]
    

    Iterating over all items in the folder is not really a good idea, moreover, you are doing that twice!

    I'd recommend using the Find/FindNextorRestrict` methods of the Items class that allow getting only items that correspond to the specified condition. Read more about these methods in the following articles: