0

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('hhh@yyy.com').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('xxx@yyy.com').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))
Dmitry Streblechenko
  • 62,942
  • 4
  • 53
  • 78
Hummer
  • 429
  • 1
  • 3
  • 16

1 Answers1

0

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)
Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
  • Thank you @Eugene. Not sure how to access a certain inbox in the list of inboxes. What about accessing a sub folder inside an Inbox that is not the default one for my email? – Hummer May 11 '21 at 22:07
  • 1
    You can use the [Store.GetRootFolder](https://learn.microsoft.com/en-us/office/vba/api/outlook.store.getrootfolder) to get the root folder and then iterate over all subfolders recursively or just get a particular folder. – Eugene Astafiev May 12 '21 at 07:37