Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to return emails within past 24 hours using ExchangeLib

I'm trying to use ExchangeLib to return all emails within an inbox within the past 24 hours. I currently have it set up to return the most recent email in the inbox, I just need help with the 24 hours part. Here is what I have so far:

credentials = Credentials('My@email', 'password')
account = Account('My@email', credentials=credentials, autodiscover=True)

for item in account.inbox.all().order_by('-datetime_received')[:1]:
    print(item.subject, item.sender.email_address)

    html = item.unique_body

    soup = BeautifulSoup(html, "html.parser")
    for span in soup.find_all('font'):
        return(item.subject, item.sender.email_address, span.text)

I've been trying to look up references on how to go about this, but I'm honestly not finding much. Any recommendations?

like image 838
JK72 Avatar asked Dec 07 '25 20:12

JK72


1 Answers

You need to add a greater-than filter on the datetime_received field:

from datetime import timedelta
from exchangelib import UTC_NOW

since = UTC_NOW() - timedelta(hours=24)
for item in account.inbox.all()\
        .filter(datetime_received__gt=since)\
        .order_by('-datetime_received'):
    # Do something
like image 97
Erik Cederstrand Avatar answered Dec 09 '25 10:12

Erik Cederstrand