Home > Enterprise >  Pywin32 not saving attachments from Outlook (Restrict.Attachements)
Pywin32 not saving attachments from Outlook (Restrict.Attachements)

Time:09-22

I am trying to download attachments from a particular sender in my Outlook inbox in python. I am using win32com.client. It seems python is finding the email I am looking for but I get the error Restrict.Attachements when trying to save. Could someone please help? Thank you

Python: 3.6.12 64bit

import win32com.client as clt
import os
from datetime import datetime, timedelta


outlook = clt.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")

inbox = mapi.GetDefaultFolder(6)

messages = inbox.Items
messages = messages.Restrict("[SenderEmailAddress] = [email protected]")

received_dt = datetime.now() - timedelta(hours=5)
received_dt = received_dt.strftime('%m/%d/%Y %H:%M %p')

for message in list(messages):
    try:
        s = message.sender
        for attachement in messages.Attachments:
            attachement.SaveASFile(os.pah.join("C:/Users/me/Desktop/", attachement.FileName))
    except Exception as e:
        print(e)

EDIT: I confirm the code finds the correct email, but in the loop it goes through the exception

>>> for message in list(messages):
...     try:
...         s = message.sender
...         for attachement in messages.Attachments:
...             attachement.SaveASFile(os.pah.join("C:/Users/me/Desktop/", attachement.FileName))
...     except Exception as e:
...         print(message.Subject, "Error: ", e)
...
TestMail Error:  Restrict.Attachments

CodePudding user response:

You need to use the message object for getting attachments, not the messages one. In the code I see the following lines:

 for attachement in messages.Attachments:
            attachement.SaveASFile(os.pah.join("C:/Users/me/Desktop/", attachement.FileName))

Instead, you need to use the following code:

 for attachement in message.Attachments:
            attachement.SaveASFile(os.pah.join("C:/Users/me/Desktop/", attachement.FileName))
  • Related