I tried to use exchangelib to extract group mailbox for analysis, and i want to extract within a date range.
tried to use Filter function but seems only work for calender, may I have your advise is there any sample for email ?
thanks all.
python exchangelib how to get email within specific date range?
Asked Answered
You need to filter on a datetime field that is available on Message items. Message.FIELDS
contains all available fields on the Message
class. You can list all datetime fields with something like:
>>> [f.name for f in Message.FIELDS if f.value_cls == EWSDateTime]
['datetime_received', 'datetime_sent', 'datetime_created', 'reminder_due_by', 'last_modified_time']
The README shows examples using .filter(start__range(x, y))
, but the start
field is only available on CalendarItem
objects. Instead, use e.g. datetime_received
to filter Message
objects:
tz = EWSTimeZone.localzone()
emails_from_2017 = account.inbox.filter(datetime_received__range=(
tz.localize(EWSDateTime(2017, 1, 1)),
tz.localize(EWSDateTime(2018, 1, 1))
))
Great thanks Erik, and thanks for your effort to create a great module –
Brittni
pytz_tz = pytz.timezone('Europe/Copenhagen') #setting the timezone
py_dt = pytz_tz.localize(datetime(year,month,day)) #building the custom date filter with a timezone object
ews_bfr = EWSDateTime.from_datetime(py_dt) #converting the custom date timezone object to a EWS (Exchange Web Service) date object
for item in account.inbox.all().order_by('-datetime_received')[:10000]: #look into the inbox the first 10K emails order desc by date received
if item.datetime_received < ews_bfr: #if the mail if older than the custom date in the EWS format then apply rule
item.delete() #delete all filtered emails
print("Mail deleted Successfully")
Please do explain the answer you have provided rather than posting code only. Also, posting an example with a delete operation is risky. Please update your example to make it more copy-paste friendly. –
Baptist
I wouldn't recommend this solution as it doesn't scale, if you have a lots of email (like > 500) it will crash. also you don't have any guaranty that it will process all emails due to the [:10000] list limit. it's better to do the filtering on server side. meaning using EWS filters. –
Chrysotile
© 2022 - 2024 — McMap. All rights reserved.