Thursday, September 23, 2021

Get messages sent on between now and last 10 days using restrict in outlook using python

 import win32com.client
import os
import time
import datetime as dt

# this is set to the current time
date_time = dt.datetime.now()
# this is set to 10 days ago
oldDate = dt.datetime.now() - dt.timedelta(days=10)
#This is set to one minute ago
newDate = dt.datetime.now() - dt.timedelta(minutes = 1)

outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
olFolder = outlook.Folders("allsourav@hotmail.com").Folders("Sent Items")

# retrieve all emails in the Sent Items, then sort them from most recently received to oldest (False will give you the reverse). Not strictly necessary, but good to know if order matters for your search
messages = olFolder.Items
messages.Sort("[ReceivedTime]", True)

# restrict to messages from the past hour based on ReceivedTime using the dates defined above.
# lastHourMessages will contain only emails with a ReceivedTime later than an hour ago
# The way the datetime is formatted DOES matter; You can't add seconds here.
last10DaysMessages = messages.Restrict("[ReceivedTime] >= '" +oldDate.strftime('%m/%d/%Y %H:%M %p')+"'")



print ("Current time: "+date_time.strftime('%m/%d/%Y %H:%M %p'))
print ("Messages from the last 10 days in Sent Items folder:")

##for message in last10DaysMessages:
##    print (message.subject,message.SentOn.strftime("%d-%m-%y"),message.ReceivedTime.strftime("%d-%m-%y"))
##    


# GetFirst/GetNext will also work, since the restricted message list is just a shortened version of your full inbox.
print ("Using GetFirst/GetNext")
message = last10DaysMessages.GetFirst()
while message:
    print (message.subject,message.SentOn.strftime("%d-%m-%y"),message.ReceivedTime.strftime("%d-%m-%y"))
    
    message = last10DaysMessages.GetNext()



Source:https://www.py4u.net/discuss/161546



No comments:

Post a Comment