【问题标题】:How to go through Outlook emails in reverse order using Python如何使用 Python 以相反的顺序浏览 Outlook 电子邮件
【发布时间】:2023-03-27 01:30:02
【问题描述】:

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

但这是从第一封电子邮件到最后一封电子邮件。我想以相反的顺序进行,因为未读的电子邮件将在顶部。有没有办法做到这一点?

【问题讨论】:

  • 那不只是改变 message = messages.GetFirst() 吗?到 messages.GetLast() 如果存在或寻找一个函数来做类似的事情
  • 是的,有一个 GetLast 和一个 GetPrevious 方法。如何以相反的顺序获得它们应该是不言而喻的......
  • GetLast()GetNext() 不能一起工作 @OmidCompSCI 我找不到 GetPrevious()。谢谢@kindall

标签: python outlook win32com


【解决方案1】:

我同意 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)

【讨论】:

    【解决方案2】:

    为什么不使用 for 循环?像您尝试做的那样从头到尾浏览您的消息。

    for message in messages:
         if message.Unread == True:
             print (message.body)
    

    【讨论】:

      最近更新 更多