user16910936
user16910936

Reputation: 1

Pulling a list of outlook email received dates using Python

I'm trying to extract a list of received dates of all emails in a specific folder within an outlook mailbox (with the intention of filtering them for specific dates later). I'm a complete beginner with Python and I've managed to get into the correct subfolder and can pull a list out, however, the list is made up of the same received date and time over and over again - the whole list is one single date. I've doubled checked this by pulling subject line and its definitely just pulling from a single email and repeating it throughout the list.

How do I get the list to comprise of all the received dates of all the emails in the folder rather than just one?

import win32com.client
import os 
from datetime import datetime, timedelta, date

outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
mailbox = outlook.Folders.Item("$OutlookMailbox")
inbox = mailbox.Folders.Item("Inbox")
pega = inbox.Folders.Item("InboxSubfolder")

messages = InboxSubfolder.Items
message = messages.GetFirst()
subject  = message.subject
sender = message.sender
received_date = message.ReceivedTime

for message in messages:
    print(received_date)

'''

I've tried: message.

and nothing is changing the output.

Upvotes: 0

Views: 5454

Answers (1)

hc_dev
hc_dev

Reputation: 9377

Issue

When do you define received_date ?

In below line marked with the comment. The line is outside the loop, and the date is from the first message. So it stays the same during the loop - unless you assign it new inside the loop.

messages = InboxSubfolder.Items
message = messages.GetFirst()
subject  = message.subject
sender = message.sender
received_date = message.ReceivedTime  # date of first message

for message in messages:
    print(received_date)

Similar solution

Have you tried:

# Count all items in the sub-folder
item_count = InboxSubfolder.Items.Count

if item_count > 0:
    for i in range(item_count, 0, -1):
        message = InboxSubfolder.Items[i]
        print(message.received_date)  # received date from current message

I found it on Python Outlook - Loop through Outlook emails in folder - pywin32 | EXCELCISE. There is a link to the GitHub repo with example iterate_emails_in_a_folder.py.

Alternative: use iterator methods (GetFirst and GetNext)

See How to go through Outlook emails in reverse order using Python

message = messages.GetFirst()
while message:  # find a suitable exit-condition!
    message = messages.GetNext()

Upvotes: 1

Related Questions