使用 Python 遍历辅助 Outlook 收件箱中的文件夹

Iterate through folders in a secondary Outlook Inbox using Python

我最大的问题是我在 Outlook 中的个人资料中附加了多个电子邮件帐户。它们都与我的主域属于同一个域。我可以像其他帐户一样发送和接收。但是,使用以下代码,我无法访问其他帐户的收件箱文件夹。只是我的默认值,即 mapi.GetDefaultFolder(6)。如何访问其他帐户的收件箱并下载我需要的附件?我试过 mapi.Folders('hhh@yyy.com').Folders('Inbox').Items 但没有用。知道如何解决这个问题吗?

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))

请改用 Store class 的 GetDefaultFolder 方法。例如:

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

这里使用了Namespaceclass的GetDefaultFolder方法。但你真正需要的是遍历所有商店并使用 Store.GetDefaultFolder 方法:

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