如何在Python中使用win32com获取主题中含有特定关键字的outlook邮件?

问题描述 投票:1回答:1

我想写一段代码,如果邮件是在过去三天内收到的,并且在主题中含有特定的关键字,那么这段代码将打印出邮件的正文。例如:在我的代码中,'approved'这个关键字。它应该列出过去三天内所有邮件的内容,主题中包含批准这个关键词。你能不能给我个建议?这是我的工作代码,只需要使用'approved'关键字进行过滤。

import win32com.client
import os
import time
import datetime as dt
from datetime import timedelta

# this is set to the current time
date_time = dt.datetime.now()

# this is set to three days ago
lastThreeDaysDateTime = dt.datetime.now() - dt.timedelta(days = 3)

outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
inbox = outlook.GetDefaultFolder(6)

# retrieve all emails in the inbox, then sort them from most recently received to oldest (False will give you the reverse). Not strictly necessary, but good to know if order matters for your search
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)

# restrict to messages from the past hour based on ReceivedTime using the dates defined above.
# lastHourMessages will contain only emails with a ReceivedTime later than an hour ago
# The way the datetime is formatted DOES matter; You can't add seconds here.

#lastHourMessages = messages.Restrict("[ReceivedTime] >= '" +lastHourDateTime.strftime('%m/%d/%Y %H:%M %p')+"'")
lastThreeDaysMessages = messages.Restrict("[ReceivedTime] >= '" +lastThreeDaysDateTime.strftime('%m/%d/%Y %H:%M %p')+"'")

#lastMinuteMessages = messages.Restrict("[ReceivedTime] >= '" +lastMinuteDateTime.strftime('%m/%d/%Y %H:%M %p')+"'")

print ("Current time: "+date_time.strftime('%m/%d/%Y %H:%M %p'))
print ("Messages from the past three days:")

#GetFirst/GetNext will also work, since the restricted message list is just a shortened version of your full inbox.

#print ("Using GetFirst/GetNext")
message = lastThreeDaysMessages.GetFirst()
while message:
    #Here needs filter which should print only those mails having approved keyword
    print (message.subject)
    print (message.body)
    message = lastThreeDaysMessages.GetNext()
python-3.x outlook win32com
1个回答
0
投票

你只需要把这两个条件结合成一个单一的 Restrict 呼叫。

lastThreeDaysMessages = messages.Restrict("[ReceivedTime] >= '" +lastThreeDaysDateTime.strftime('%m/%d/%Y %H:%M %p')+"' AND "urn:schemas:httpmail:subject" ci_phrasematch " & "'approved'")

阅读更多关于这一点在 为查找和限制方法创建过滤器 MSDN中的部分。


0
投票

下面是一个用特定主题搜索邮件的例子。我在项目中使用了名为exchangeelib的python库。虽然我的目的是不同的,但我相信exchangeelib也许能帮助你。

https:/medium.com@theamazingexposureaccessing-shared-mailbox-using-exchangeelib-python-f020e71a96ab。

以下是我使用 exchangeelib 来查找具有特定主题的最新邮件的 python 代码段。

for item in account.inbox.filter(subject__contains='数据已准备就绪').order_by('-datetime_received')[:1]。

© www.soinside.com 2019 - 2024. All rights reserved.