Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to go through Outlook emails in reverse order using Python

I want to read my Outlook emails and only the Unread ones. The code that I have right now is:

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

But this goes from the first email to last email. I want to go in the reverse order because unread emails will be on the top. Is there a way to do that?

like image 319
Suraj Nagabhushana Ponnaganti Avatar asked Oct 16 '25 14:10

Suraj Nagabhushana Ponnaganti


2 Answers

I agree with cole that a for loop is good for going through all of them. If starting from the most recently-received email is important (e.g. for a specific order, or for limiting how many emails you go through), you can use the Sort function to sort them by the Received Time property.

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)
like image 169
Bex Way Avatar answered Oct 18 '25 07:10

Bex Way


Why not use a for loop? To go through your messages from first to last like it appears you are trying to do.

for message in messages:
     if message.Unread == True:
         print (message.body)
like image 37
cole Avatar answered Oct 18 '25 08:10

cole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!