使用python连接到outlook并读取电子邮件和附件,然后将它们写入输出fi

2024-05-19 21:56:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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()

没有代码中的附件-它工作得很好。我可以阅读我特定子文件夹中的所有电子邮件。在

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


Tags: csvimportclientmessageoutput附件attachment电子邮件
1条回答
网友
1楼 · 发布于 2024-05-19 21:56:55

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

相反,请使用以下方法:

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

我希望这有帮助!在

相关问题 更多 >