C#代码无法获取用户邮件文件夹,但Graph Explorer可正常获取
我的目标是读取任意用户的Office 365 Outlook邮件及附件,并通过筛选条件删除特定邮件。我已在Azure AD中创建应用,配置了Graph应用权限并获得管理员同意,参考截图如下。我能通过Graph Explorer使用API https://graph.microsoft.com/v1.0/users/testuser@outlook.com/messages 获取邮件,但克隆GitHub的守护程序示例项目并扩展功能后,仅能获取Azure AD用户列表,无法获取指定用户的邮件。扩展代码如下:
private static async Task CallMSGraphUsingGraphSDK(IConfidentialClientApplication app, string[] scopes) { // Prepare an authenticated MS Graph SDK client GraphServiceClient graphServiceClient = GetAuthenticatedGraphClient(app, scopes); try { string name = "ANYUSER@outlook.com"; //Listing All Users var users = await graphServiceClient.Users.Request().GetAsync(); foreach (var user in users) { Console.WriteLine($"{user.Id}, {user.GivenName} {user.Surname}, {user.MemberOf}, {user.UserPrincipalName}, {user.Mail}"); } //Trying to get any user outlook messages. var userdetails = await graphServiceClient.Users.Request().Filter($"mail eq '{name}'").GetAsync(); Console.WriteLine($"Hello, {userdetails.FirstOrDefault().DisplayName}"); // Get the first user's mail folders var mailFolders = await graphServiceClient .Users[userdetails[0].Id].Messages.Request().GetAsync(); var inboxMail = await graphServiceClient.Users[userdetails.FirstOrDefault().Id].MailFolders.Inbox.Messages.Request().GetAsync(); foreach (var mail in inboxMail.CurrentPage.ToList()) { Console.WriteLine("From: {0}\nSubject: {1}\nBody:\n{2}\n--------------------\n", mail.From.EmailAddress.Address, mail.Subject, mail.BodyPreview); } } catch (ServiceException e) { Console.WriteLine("Exception Caught: " + $"{e}"); } }
我使用的是Graph SDK,相关截图如下。请问我哪里操作出错了?
以下是几个可能导致你无法获取指定用户邮件的原因及对应解决方法:
检查请求的权限范围(Scopes)
守护程序模式必须使用应用权限,且需包含读取邮件的权限(如Mail.Read.All、Mail.ReadWrite.All)。确认初始化客户端时传入的scopes参数是否为new[] { "https://graph.microsoft.com/.default" }——应用权限模式下需用.default来获取所有已配置的权限,而非委托权限的scopes。验证用户标识的正确性
- 确认目标用户的
mail属性确实是ANYUSER@outlook.com,部分用户的UserPrincipalName与mail属性可能不一致。可直接使用用户的UserPrincipalName或Id调用API,比如graphServiceClient.Users["testuser@outlook.com"].Messages.Request().GetAsync(),避免筛选逻辑出错。 - 在访问
userdetails[0].Id或FirstOrDefault()前,先判断集合是否为空,防止空引用异常。
- 确认目标用户的
处理Graph API的分页机制
Graph API默认最多返回100条结果并分页,你当前仅读取了CurrentPage。若目标用户收件箱邮件超过100条,需通过NextPageRequest获取后续页面,示例代码:var inboxMail = await graphServiceClient.Users[userId].MailFolders.Inbox.Messages.Request().GetAsync(); do { foreach (var mail in inboxMail) { Console.WriteLine("From: {0}\nSubject: {1}\nBody:\n{2}\n--------------------\n", mail.From.EmailAddress.Address, mail.Subject, mail.BodyPreview); } inboxMail = inboxMail.NextPageRequest != null ? await inboxMail.NextPageRequest.GetAsync() : null; } while (inboxMail != null);查看详细的异常信息
当前仅打印了ServiceException对象,建议输出e.Message、e.StatusCode、e.ResponseBody等详细内容,这些信息能直接定位API调用失败的原因(如权限不足、用户不存在、请求格式错误等)。确认Graph SDK版本
确保使用的是最新版本的Microsoft Graph SDK,旧版本可能存在API兼容性问题。可通过NuGet更新Microsoft.Graph和Microsoft.Graph.Auth包。
内容的提问来源于stack exchange,提问作者PavanKumar GVVS

