我想阅读我的Outlook电子邮件,而仅阅读未阅读的电子邮件。我现在拥有的代码是:
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetFirst ()
while message:
if message.Unread == True:
print (message.body)
message = messages.GetNext ()
这从第一封电子邮件到最后一封电子邮件。我想以相反的顺序进行,因为未读的电子邮件将位于顶部。有办法做到吗?
我同意科尔(Cole)的观点,即循环对所有这些都有好处。如果从最近收到的电子邮件开始很重要(例如,对于特定订单或限制您通过多少电子邮件),则可以使用Sort功能通过接收到的时间属性对它们进行排序。
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
#the Sort function will sort your messages by their ReceivedTime property, from the most recently received to the oldest.
#If you use False instead of True, it will sort in the opposite direction: ascending order, from the oldest to the most recent.
messages.Sort("[ReceivedTime]", True)
for message in messages:
if message.Unread == True:
print (message.body)
为什么不使用循环?要从第一到最后一个消息,就像您正在尝试做的那样。
for message in messages:
if message.Unread == True:
print (message.body)
有点旧问题,但这是该问题的Google上最重要的帖子之一,所以我想添加我的经验。
通过消息迭代中使用循环是" Pythonic"。构造代码的方法,但是根据我的经验,它通常会导致此特定库/API的失败,因为任何外部更改(例如,在迭代时将电子邮件移至另一个文件夹)可能会导致可怕的4096例外。
此外,您还会发现任何非email(例如,会议邀请)都会导致意外结果/异常。
i因此,使用代码是原始海报代码的网格,BEX方法的接受答案和我自己的发现:
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
message = messages.GetFirst ()
while message:
if message.Class != 43: #Not an email - ignore it
message = messages.GetNext ()
elif message.Unread == True:
print (message.body)
message = messages.GetNext ()