如何使用Python倒序浏览Outlook电子邮件

3

我想阅读我的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 ()

但这是按照第一封电子邮件到最后一封电子邮件的顺序排列的。我想按相反的顺序排列,因为未读邮件将显示在顶部。有办法做到这一点吗?


那么,如果存在 messages.GetLast() 函数,将 message = messages.GetFirst() 更改为 messages.GetLast() 是否更好?或者寻找一个类似的函数来实现相似的功能。 - Omid CompSCI
3
是的,有一个GetLast方法和一个GetPrevious方法。如何以相反的顺序获得它们应该是不言自明的... - kindall
GetLast()GetNext() 不能同时使用,@OmidCompSCI 和我找不到 GetPrevious()。谢谢 @kindall。 - Suraj Nagabhushana Ponnaganti
3个回答

13

我同意Cole的观点,使用for循环可以遍历所有电子邮件。如果从最近收到的电子邮件开始很重要(例如,针对特定顺序或限制遍历的电子邮件数量),您可以使用Sort函数按照Received Time属性对它们进行排序。

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)

1
为什么不使用for循环?像您似乎试图做的那样,从头到尾遍历您的消息。
for message in messages:
     if message.Unread == True:
         print (message.body)

0

这是一个有点陈旧的问题,但在谷歌上此问题是热门帖子之一,我想分享我的经验。

使用for循环来遍历消息是一种更符合"Python风格"的编码方式,但根据我的经验,在这个特定的库/接口中它经常导致故障,因为任何外部变化(比如在程序遍历时将电子邮件移动到另一个文件夹)都可能引发可怕的4096异常。

此外,你会发现任何非电子邮件(比如会议邀请)都可能导致意外结果或异常。

因此,我使用的代码是原帖作者的代码、Bex Way的被接受回答以及我自己的发现的混合体:

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 ()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接