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