使用 Python 从 Outlook 读取电子邮件并指定日期范围

Reading Emails From Outlook with Python & Specifying a Date Range

我正在尝试使用特定日期范围以及其他条件(发件人、主题等)从 Outlook 读取电子邮件。但是,我不确定如何指定 Python 可以在其中指定的日期范围搜索电子邮件。这是我到目前为止产生的类型错误:

if subject in message.subject and date in message.senton.date():
TypeError: argument of type 'datetime.date' is not iterable
import win32com.client
import datetime


outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

inbox = outlook.GetDefaultFolder(18).Folders.Item("xxxxx")
messages = inbox.Items
date = datetime.date.today()


subject = "xxxxxxx"

for message in messages:
    if subject in message.subject and date in message.senton.date():
     print(message.senton.time())

我想搜索特定日期范围内的电子邮件,并且能够使用多个条件进行搜索。例如指定主题和发件人等。但我不确定如何,我是 Python 的新手所以请帮助!

试试这个

if subject in message.subject and date == message.senton.date():
     print(message.senton.time())
     print(message.sender)

编辑: 如果你想要日期范围,你可以使用 datetime 来定义日期范围

start = message.senton.date() - timedelta(days=10)
end = message.senton.date() + datetime.timedelta(days=10) # 20 days date range
if subject in message.subject and date > start and date < end:
     print(message.senton.time())
     print(message.sender)

outlook 提供了一个 api 来查询确切的主题,而不是遍历每条消息:

import win32com.client
    
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox=outlook.Folders.Item(3).Folders['Inbox'].Folders['My Folder']
filt = "@SQL=""http://schemas.microsoft.com/mapi/proptag/0x0037001f"" = '{0}'".format(subject)
messages=inbox.Items.Restrict(filt)