我有一些代码可以根据特定条件在一组Outlook收件箱中进行搜索,并检索满足指定条件的电子邮件的日期和时间。此代码还会下载电子邮件中的第一个附件。
import win32com.client
from datetime import date, timedelta
import os
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(18).Folders.Item("xxx")
messages = inbox.Items
path = os.path.expanduser("C:\\Users\\User\\Documents"
"\\Projects\\Python Projects\\Email Classification\\Email Attachments")
dateHigh = date.today() - timedelta(days=45)
dateLow = date.today() - timedelta(days=-0)
subject = "xxxxxxxx"
max = 100000
for count, message in enumerate(messages):
if count > max:
break
if subject in message.subject and message.senton.date() > dateHigh and message.senton.date() < dateLow:
print(message.senton.date())
print(message.senton.time())
print(message.subject)
attachments = message.Attachments
attachment = attachments.Item(1)
for attachment in message.Attachments:
if attachments.Count > 0:
attachment.SaveASFile(path + '\\' + str(attachment))
break
我期望下载并存储电子邮件附件(pdf / csv)文件,但是,仅从电子邮件中下载图像。如何下载电子邮件中的其他附件?
答案 0 :(得分:1)
在python调试器中尝试以下代码。附件是否保存?
import win32com.client
import os
from os.path import expanduser
home = expanduser("~")
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("18")
all_inbox = inbox.Items
save_folder = os.path.join(home, "attach")
if not(os.path.exists(save_folder)):
os.mkdir(save_folder)
for msg in all_inbox:
print(msg.Subject)
for att in msg.Attachments:
print(att.FileName)
print(msg.Attachments.Count)
att.SaveASFile(os.path.join(save_folder, str(att.FileName)))