Exchangelib 扫描所有文件夹 - 效率

问题描述

我正在使用 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)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...