0

How can I make an alert/exception, if an email isn't found the past 24 hours?

This is the printed output, if there is an email found. It prints the email-address, subject and count. In one line

defaultdict(<class 'int'>, {('info@something.com', 'Backup status report (Error): Tesla (D) (Monday, 14/09/2020)'): 1})

this is the printed output if nothing is found.

defaultdict(<class 'int'>, {})

from exchangelib import Credentials, Account, UTC_NOW
from collections import defaultdict
from datetime import timedelta



credentials = Credentials('something@something.dk', 'private')
a = Account('something@something.dk', credentials=credentials, autodiscover=True)
counts = defaultdict(int)
testfolder = a.inbox.parent / 'Test'
since = UTC_NOW() - timedelta(hours=24)

for item in testfolder.all()\
        .only('sender', 'subject')\
        .filter(datetime_received__gt=since)\
        .order_by('-datetime_received'):
    if item.sender.email_address == 'info@something.com':
        counts[item.sender.email_address, item.subject] += 1
    if not testfolder.filter(datetime_received__gt=since,
            sender='info@something.com').exists():
                print('no email found')
print(counts)

Edited above code to the below answer, but it still prints the empty dictionary

fazzerking
  • 23
  • 7

1 Answers1

0

Filtering on sender is supposed to work, although I can't get it to work right now on my test account. Here's how I would do an efficient query that just gives you the information you need:

from datetime import timedelta
from exchangelib import Credentials, Account, UTC_NOW

credentials = Credentials('something@something.dk', 'private')
a = Account('something@something.dk', credentials=credentials, autodiscover=True)
since = UTC_NOW() - timedelta(hours=24)
testfolder = a.inbox.parent / 'Test'
if not testfolder.filter(
    datetime_received__gt=since, 
    sender='info@something.com',
).exists():
    print('No email found!')
Erik Cederstrand
  • 9,643
  • 8
  • 39
  • 63