0

I am trying to read emails from Outlook using a specific date range as well as other criteria - sender, subject etc. However, I am unsure as to how to specify a date range within which Python can search for the emails. This is what I have so far which generates the type error below:

if subject in message.subject and date in message.senton.date():
TypeError: argument of type 'datetime.date' is not iterable
import win32com.client
import datetime


outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

inbox = outlook.GetDefaultFolder(18).Folders.Item("xxxxx")
messages = inbox.Items
date = datetime.date.today()


subject = "xxxxxxx"

for message in messages:
    if subject in message.subject and date in message.senton.date():
     print(message.senton.time())

I would like to search for emails within a specific date range, as well as be able to use more than one criteria to search. E.g specify the subject as well as sender etc. But I am not sure how, I am new to Python so please help!

Saadiq
  • 101
  • 2
  • 15

2 Answers2

1

Try this

if subject in message.subject and date == message.senton.date():
     print(message.senton.time())
     print(message.sender)

Edit: if you want date range you can use datetime to define the date range

start = message.senton.date() - timedelta(days=10)
end = message.senton.date() + datetime.timedelta(days=10) # 20 days date range
if subject in message.subject and date > start and date < end:
     print(message.senton.time())
     print(message.sender)
Z.Amir
  • 195
  • 1
  • 12
  • Hey, thanks for your response. Your initial suggestion works however, when trying to print message.senton.time() and print message.sender. It only prints one, whichever is specified first – Saadiq May 10 '19 at 11:55
  • how are you printing it? have you checked the indentation? – Z.Amir May 10 '19 at 11:57
  • if subject in message.subject and date == message.senton.date(): print(message.sender) and print(message.senton.time()) – Saadiq May 10 '19 at 12:03
  • Thats what my print line looks like, I know you cant check indentation on here but i'm using PyCharm and its not bringing up any indentation errors – Saadiq May 10 '19 at 12:03
  • I have edited the comment to add print statement. This should work – Z.Amir May 10 '19 at 12:32
  • You should maybe try debugging your code, you can use IDE for that or python pdb. – Z.Amir May 10 '19 at 12:35
1

instead of looping through every message, outlook provides an api to query the exact subject:

import win32com.client
    
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox=outlook.Folders.Item(3).Folders['Inbox'].Folders['My Folder']
filt = "@SQL=""http://schemas.microsoft.com/mapi/proptag/0x0037001f"" = '{0}'".format(subject)
messages=inbox.Items.Restrict(filt)