问题描述
我正在使用 exchangelib 连接到我的交换邮箱。目前代码正在扫描所有文件夹,因为目标电子邮件可以位于我的任务的任何文件夹中。
是否有更有效的方法来循环/扫描此处的文件夹? (查找大于目标开始日期的电子邮件)
folder = account.root
all_folders = folder.glob('**/*')
for folder in all_folders:
if folder.folder_class == 'IPF.Note': #Messages can only exist in 'IPF.Note' folder classes
for email in folder.filter(datetime_received__gt=ews_bfr): #For all emails that are newer than the target date
编辑: 谢谢你的帮助,埃里克。这有效并显着减少了运行时间:
target_folders = FolderCollection(account=account,folders=(f for f in account.root.walk() if f.name in ['xxxxxx']))\
.filter(datetime_received__gt=ews_bfr)
for email in target_folders:
解决方法
普通的 .filter()
仅作用于您调用它的文件夹。 EWS 不支持在所有文件夹中搜索项目,而仅支持在 FindItems
服务调用中明确提及的文件夹。
在exchangelib中,一次性过滤多个文件夹的方法是使用FolderCollection
:
from exchangelib import FolderCollection
FolderCollection(account=account,folders=[...]).filter(some_field='foo')
folders
参数可以是任何可迭代的文件夹,例如[account.inbox,account.sent]
、account.root.walk()
或 (f for f in account.root.walk() if f.CONTAINER_CLASS == 'IPF.Note')
.glob()
、.walk()
、.children
和其他子文件夹访问方法也支持对它们调用 .filter()
:
account.root.glob('**/*').filter(datetime_received__gt=ews_bfr)
account.root.walk().filter(datetime_received__gt=ews_bfr)