使用GraphServiceClient获取Outlook邮件的筛选及附件相关问题
问题解决与代码优化
1. 筛选条件不生效的修复
你的筛选逻辑错误在于使用QueryOption直接传递参数,Microsoft Graph API的筛选需要通过Filter()方法指定$filter参数,同时注意以下细节:
- 日期需带UTC时区标识
Z,避免时间偏差 HasAttachments是区分大小写的布尔属性,必须用eq true明确判断- 多条件用
and连接
修改后的核心查询代码:
pagedMessages = await _graphServiceClient.Me.Messages .Request() .Filter("ReceivedDateTime ge 2022-01-01T00:00:00Z and ReceivedDateTime le 2022-10-12T23:59:59Z and HasAttachments eq true") .Select(msg => new { msg.Subject, msg.BodyPreview, msg.ReceivedDateTime, msg.HasAttachments, msg.Attachments, msg.Id }) .Expand("attachments") .Top(50) // 保留分页大小,后续循环拉取全部 .OrderBy("receivedDateTime desc") .GetAsync();
2. 获取全部邮件(处理分页)
Graph API默认分页返回数据,单次最多支持999条,需要循环获取下一页直到没有更多数据:
// 存储所有邮件的集合 var allMessages = new List<dynamic>(); do { allMessages.AddRange(pagedMessages.CurrentPage); // 检查并拉取下一页 if (pagedMessages.NextPageRequest != null) { pagedMessages = await pagedMessages.NextPageRequest.GetAsync(); } else { break; } } while (true); // 遍历所有邮件处理附件 foreach (var item in allMessages) { if (item.Attachments != null && item.Attachments.Any()) { foreach (var attachment in item.Attachments) { if (attachment.ODataType == "#microsoft.graph.fileAttachment") { FileAttachment fileAttachment = attachment as FileAttachment; byte[] contentBytes = fileAttachment.ContentBytes; // 此处添加附件处理逻辑 } } } }
3. 关于.Expand("attachments")的作用
是的,添加.Expand("attachments")后无需单独调用附件API。该方法会将附件数据直接内嵌在返回的邮件对象中,可直接通过item.Attachments访问附件信息(包括FileAttachment的ContentBytes)。
如果邮件附件数量极多,可通过.Expand("attachments($top=100)")指定单次返回的附件数量,避免数据过载。
内容的提问来源于stack exchange,提问作者Vishal Kiri
相关产品推荐
相关产品推荐

