Search code examples
pythonoutlookpywin32win32com

Iterate through folders in a secondary Outlook Inbox using Python


My biggest issue is that I have several email accounts attached to my profile in Outlook. They all belong to the same domain as my main one. I'm able to send and receive as the other accounts. However, with the below code, I'm not able to access the Inbox folders of the other accounts. Just my default one i.e. mapi.GetDefaultFolder(6). How can I access inboxes of the other accounts and download the attachments as that's what I need? I tried mapi.Folders('[email protected]').Folders('Inbox').Items and that didn't work. Any idea of how to work this out?

import win32com.client
import pendulum

outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")
Inbox = mapi.GetDefaultFolder(6) #Can be  replaced with Messages = mapi.Folders('[email protected]').Folders('Inbox').Items . If this  happens, then no need to define  Messages below.
Messages = Inbox.Items


received_date = pendulum.now().last(pendulum.MONDAY) #Search for emails since last Monday
received_date = received_date.strftime('%m/%d/%Y %H:%M %p') #Change  the date format
messages = Messages.Restrict("[ReceivedTime] >= '" + received_date + "'") #Restrict the received time i.e. > than or equal to last Monday
messages = Messages.Restrict("[Subject] = 'Automatic Reports'") #Title  contains   this 

outputDir = r"C:\Users\xxx\TestEmails"
try:
    for message in list(messages):
        try:
            s = message.sender
            for attachment in message.Attachments:
                attachment.SaveASFile(os.path.join(outputDir, attachment.FileName))
                print(f"attachment {attachment.FileName} from {s} saved")
        except Exception as e:
            print("error when saving the attachment:" + str(e))
except Exception as e:
    print("error when processing emails messages:" + str(e))

Solution

  • Use the GetDefaultFolder method of the Store class instead. For example:

    mapi = outlook.GetNamespace("MAPI")
    Inbox = mapi.GetDefaultFolder(6)
    

    Here the GetDefaultFolder method of the Namespace class is used. But what you really need is to iterate over all stores and use the Store.GetDefaultFolder method:

    mapi = outlook.GetNamespace("MAPI")
    for store in mapi.Stores: 
      Inbox = store.GetDefaultFolder(6)