Search code examples
pythonloopsexchangelib

Python loop not iterating through the list


I have this code, where I'm trying to loop through a mailbox with specified email-adresses in a list, but instead I'm getting the output of all email-adresses. When I print the counts, I get like 10 different email adresses, but not the ones I've limited to in the lists. How do I make it print only the ones from my list "emails"

from exchangelib import Credentials, Account
from collections import defaultdict

emails = ['test1@random.com','test2@random.com']

for email in emails:
    credentials = Credentials('hidden@hidden.com', 'hiddenpass')
    account = Account('hidden@hidden.com', credentials=credentials, autodiscover=True)
    counts = defaultdict(int)
    for item in account.inbox.all().order_by('-datetime_received')[:100]:
        counts[item.sender.email_address] += 1
print(counts)

Solution

  • You don't need to iterate on the emails list. If you want to filter emails that don't appear in the emails list, you can do something like:

    for item in account.inbox.all().order_by('-datetime_received')[:100]:
        if item.sender.email_address in emails:
            counts[item.sender.email_address] += 1
    

    I'm not familiar with this library, but maybe you have the option to grab only the relevant results with something similar to:

    account.inbox.all().filter(sender=email).order_by('-datetime_received')
    

    As noted by @erikcederstrand, you can get better performance if you fetch only senders:

    account.inbox.all().order_by('-datetime_received').only('sender')