【问题标题】:Reading Emails From Outlook with Python & Specifying a Date Range使用 Python 从 Outlook 读取电子邮件并指定日期范围
【发布时间】:2019-05-10 10:06:32
【问题描述】:

我正在尝试使用特定日期范围以及其他条件(发件人、主题等)从 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 新手,所以请帮忙!

【问题讨论】:

    标签: python outlook-api


    【解决方案1】:

    试试这个

    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)
    

    【讨论】:

    • 您好,感谢您的回复。但是,在尝试打印 message.senton.time() 和打印 message.sender 时,您的初始建议有效。它只打印一个,以先指定者为准
    • 如何打印?你检查过缩进吗?
    • 如果 message.subject 中的主题和日期 == message.senton.date():print(message.sender) 和 print(message.senton.time())
    • 这就是我的打印线的样子,我知道你不能在这里检查缩进,但我使用的是 PyCharm,它没有出现任何缩进错误
    • 我已经编辑了评论以添加打印语句。这应该工作
    【解决方案2】:

    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)
    

    【讨论】:

      猜你喜欢
      • 2021-10-22
      • 2021-08-13
      • 2019-11-25
      • 2021-10-26
      • 1970-01-01
      • 2011-07-01
      • 2018-07-22
      • 2019-07-26
      • 1970-01-01
      相关资源
      最近更新 更多