我有这段代码,我试图在列表中循环浏览具有指定电子邮件地址的邮箱,但我却得到了所有电子邮件地址的输出。当我打印计数时,我会得到10种不同的电子邮件地址,但不是仅限于列表中的地址。如何使其仅打印“电子邮件”列表中的那些邮件
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)
答案 0 :(得分:1)
您无需在emails
列表上进行迭代。如果要过滤未出现在emails
列表中的电子邮件,可以执行以下操作:
for item in account.inbox.all().order_by('-datetime_received')[:100]:
if item.sender.email_address in emails:
counts[item.sender.email_address] += 1
我对这个库不熟悉,但是也许您可以选择仅获取与以下内容类似的相关结果:
account.inbox.all().filter(sender=email).order_by('-datetime_received')
如@erikcederstrand所述,如果仅提取发件人,则可以获得更好的性能:
account.inbox.all().order_by('-datetime_received').only('sender')
答案 1 :(得分:0)
也许您应该尝试以下操作(如果我理解正确的话)。我们像以前一样增加count变量,但仅打印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
if item.sender.email_address in emails:
print(item.sender.email_address)
print(counts[item.sender.email_address])