0

I'm trying to write a script in Python to read all the subject headers, in a range date... but it doesn't work!

I have tried different solution to read emails in this range but I could not find a better option than restrict, I also tried to use [LastModificationTime]

DATA_RANGE_EMAIL = "[SentOn] > '10/01/2019 00:01 AM' AND [SentOn] < '10/10/2019 08:00 AM'"
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
utente = outlook.Folders("myaccount@myemail.com")
inbox = utente.folders("Inbox")
CRQ = inbox.folders("CRQ")
messages = CRQ.Items.restrict(DATA_RANGE_EMAIL)
message = messages.GetFirst ()
while message:
    sub = message.subject.encode("utf-8")
    print(sub)
    message_IN = messages.GetNext ()

Now the script read ALL the email, and not just the email in that range... What am I doing wrong?

Thank you to everyone who gives me some advice!

Torbak
  • 1
  • 1

1 Answers1

1

I solved it by delimiting the start and endpoints with datetime objects quite easily. The only problem is that the datetime-objects from the MailItem-objects have a timezone attached (tzinfo), which I had to remove for the comparison with > and < to work. But, since this is a non-writable subclass, I had to work around that limitation by creating a new datetime object from scratch and filling it with its values.

import win32com.client as win32
import datetime

dateRange_StartOn = datetime.datetime(2019, 10, 1, 0, 1)
dateRange_UpTo =  datetime.datetime(2019, 10, 10, 8, 0)
outlook = win32.Dispatch("Outlook.Application").GetNamespace("MAPI")
acc = outlook.Folders("myemail@myprovide.com")
inbox = acc.folders("Inbox") #Language-specific to the users GUI. "Inbox" is not a universal, internally fixed name

def tzInfo2Naive(in_dtObj): #Convert the tzInfo of the datetime object to naive (none)
    return datetime.datetime(in_dtObj.year,in_dtObj.month,in_dtObj.day,in_dtObj.hour,in_dtObj.minute)

for message in inbox.Items:
    sub = message
    timeReceived = message.ReceivedTime #datetime-object
    timeReceived = tzInfo2Naive(timeReceived)
    if timeReceived > dateRange_StartOn and timeReceived < dateRange_UpTo:
        print("%s :: %s" % (str(timeReceived), sub))
tst
  • 371
  • 1
  • 11