如何使用Python版MS Graph SDK按时间范围查询邮件?
解决MS Graph Python SDK筛选特定时间范围邮件的问题
要筛选特定时间范围内的邮件,只需在MessagesRequestBuilderGetQueryParameters中添加filter参数,使用Graph API支持的日期筛选语法即可。
修改后的完整代码如下:
MAIL_FOLDER_ID = "inbox" SELECT_FIELDS = [ "id", "webLink", "from", "toRecipients", "receivedDateTime", "subject", "body", "lastModifiedDateTime", "hasAttachments", "attachments", "bodyPreview", ] TOP_VALUE = 1000 ORDER_BY = ["receivedDateTime DESC"] SCOPES = ["https://graph.microsoft.com/.default"] # 定义时间范围筛选条件,使用ISO 8601 UTC格式 START_DATE = "2024-01-01T00:00:00Z" END_DATE = "2024-06-01T23:59:59Z" FILTER_CONDITION = f"receivedDateTime ge '{START_DATE}' and receivedDateTime le '{END_DATE}'" query_params = ( MessagesRequestBuilder.MessagesRequestBuilderGetQueryParameters( select=SELECT_FIELDS, top=TOP_VALUE, orderby=ORDER_BY, filter=FILTER_CONDITION # 新增筛选参数 ) ) self.request_config = ( MessagesRequestBuilder.MessagesRequestBuilderGetRequestConfiguration( query_parameters=query_params ) ) page = ( await self.graphClient .me .mail_folders.by_mail_folder_id(MAIL_FOLDER_ID) .messages.get(request_configuration=self.request_config) )
关键说明:
- 筛选语法:使用
receivedDateTime字段配合ge(大于等于)、le(小于等于)运算符组合时间范围,条件需用单引号包裹日期字符串 - 日期格式:必须使用ISO 8601格式的UTC时间(结尾带
Z),避免时区差异导致的筛选错误 - 参数位置:
filter是MessagesRequestBuilderGetQueryParameters的内置参数,直接传入即可生效
内容的提问来源于stack exchange,提问作者WHOATEMYNOODLES
相关产品推荐
相关产品推荐

