爬取outlook邮件

背景:工作中遇到需求,获取outlook邮箱中某段时间的邮件附件,本地存储

import win32com.client as win32
import os
import datetime

outlook = win32.Dispatch('outlook.application') # 获取outlook句柄

mapi = outlook.GetNamespace('MAPI') # 获取API

messages = mapi.Folders("test@qq.com").Folders("收件箱").Items # 收件箱所有邮件


start_date = datetime.datetime(2022, 12, 30)

end_date = datetime.datetime(2023, 1, 1)

WoYaoDeYouJian = messages.Restrict("[ReceivedTime] >= '" + start_date.strftime('%m/%d/%Y %H:%M %p') + "' AND [ReceivedTime] <= '" + end_date.strftime('%m/%d/%Y %H:%M %p') + "'") # 筛选出2019年至今的邮件

outputDir = r"D:\attachment"

try:
for message in list(WoYaoDeYouJian):
try:
s = message.sender
for attachment in message.Attachments:
attachment.SaveASFile(os.path.join(outputDir, attachment.FileName))
print(f"attachment {attachment.FileName} from {s} saved")
print(message.ReceivedTime)
except Exception as e:
print(str(e))
except Exception as e:
print(str(e))

  

posted @ 2022-11-26 12:15  队长给我球  阅读(105)  评论(0编辑  收藏  举报