[英]Downloading Email Attachments with Python - When there's more than one attachment
我有基於特定條件在一組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)文件,但是,僅下載了電子郵件中的圖像。 如何下載電子郵件中的其他附件?
在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)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.