如何迭代 outlook 文件夹中的电子邮件并将其放入每封电子邮件的 csv 文件中?

How to iterate emails in a outlook folder and put it in a csv file per email?

我有一个文件夹,我想遍历电子邮件并将每封电子邮件的元数据保存到 csv 文件。

我希望 csv 输出如下所示:

emailSubject, sender,   senderEmailAddress
<subject>,    <sender>,       <senderEmailAddress>

到目前为止,这是我的代码:

import win32com.client

# Input
results = {}
f = open("testfile.txt", "w+")
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders.Item("Test Folder")
inbox = folder.Folders.Item("Inbox")
msg = inbox.Items

# Process
for x in msg:
    senderEmail = x.SenderEmailAddress
    sender = x.Sender
    subject = x.Subject

我是 python 的新手,在添加代码段以将每个元素添加到 csv 文件时遇到问题。任何建议或想法将不胜感激!

如果您的其余代码工作令您满意,您可以使用 CSV module 编写您想要的文件。

import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders.Item("Test Folder")
inbox = folder.Folders.Item("Inbox")
msg = inbox.Items

f = open("testfile.txt", "w", newline="")
writer = csv.writer(f)
writer.writerow(["emailSubject", "sender", "senderEmailAddress"])

# Process
for x in msg:
    senderEmail = x.SenderEmailAddress
    sender = x.Sender
    subject = x.Subject
    writer.writerow([subject, sender, senderEmail])

f.close()