python - 使用 python 连接到 Outlook 并读取电子邮件和附件,然后将其写入输出文件

标签 python pandas

我正在尝试使用 python 连接到 Outlook 并读取电子邮件并将它们与所有相应的附件一起写入输出文件。

这是我到目前为止所拥有的:

import win32com.client
import unicodecsv as csv
import os

output_file = open('./outlook_farming_001.csv','wb')
output_writer = csv.writer(output_file, delimiter=';', encoding='latin2')

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders.Item("Security Availabilities")
messages = inbox.Items

for i, message in enumerate(messages):
    try:

        sender = message.SenderName
        sender_address = message.SenderEmailAddress
        sent_to = message.To
        date = message.LastModificationTime
        subject = message.subject
        body = message.body

        attachments = message.Attachments
        attachment = attachments.Item(1)
        for attachment in message.Attachments:
            attachment.SaveAsFile(os.path.join(output_file, str(attachment)))

        output_writer.writerow([
            sender,
            sender_address,
            subject,
            body,
            attachment])

    except Exception as e:
        ()

output_file.close()

如果代码中没有附件,它就可以正常工作。我可以阅读特定子文件夹中的所有电子邮件。

但是,我无法阅读、保存和显示附件及其相应的电子邮件。

最佳答案

我认为你的错误在于使用 str(attachment)在文件名中 - 这会引起麻烦,因为它应该给出某种 '<COMObject <unknown>>'字符串。

相反,请使用以下内容:

    for attachment in message.Attachments:
        attachment.SaveAsFile(os.path.join(output_file, attachment.FileName))

希望这会有所帮助!

关于python - 使用 python 连接到 Outlook 并读取电子邮件和附件,然后将其写入输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55654922/

相关文章:

python - 将不规则列表的单列数据框分解为多列

python - 如何检查网站的 SSLv2 或 SSLv3?

python - 如何按名称作为变量访问列以使用 isin() 方法

python - Pandas 按条件按列值排名

python - 图像直方图的高斯混合模型

python - Pandas 读取json ValueError : Protocol not known

python - 在 pandas 中检查一个数据帧与另一个数据帧的值的快速方法

python - 使用 2 个标识符合并数据帧

python - 有没有一种简单的方法可以在最后一个数据框中包含第一个值之前的值?

python - 在 Python 中重置生成器对象