保存 Outlook 电子邮件

Saving Outlook Emails

我设法获得了 GopiKrishna 发布的以下代码。它适用于我,但它只保存我 Outlook 中的第一封电子邮件。

我只是想知道对代码进行细微调整是否有助于将所有 Outlook 电子邮件保存在收件箱 and/or 其他文件夹中。

from win32com.client import Dispatch
import os
import re
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
print(inbox)
messages = inbox.items
message = messages.GetLast()
name = str(message.subject)
#to eliminate any special charecters in the name
name = re.sub('[^A-Za-z0-9]+', '', name)+'.msg'
#to save in the current working directory
message.SaveAs(os.getcwd()+'//'+name)

您将需要 运行 for 循环

例子

from win32com.client import Dispatch
import os
import re


def save_emails():
    for message in inbox.Items:
        if message.Class == 43:
            name = str(message.Subject)
            # to eliminate any special characters in the name
            name = re.sub('[^A-Za-z0-9]+', '', name) + '.msg'
            # to save in the current working directory
            message.SaveAs(os.getcwd() + '//' + name)


if __name__ == '__main__':
    outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
    inbox = outlook.GetDefaultFolder(6)
    save_emails()