You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Microsoft Graph获取Office365邮件时返回400错误请求

解决客户端凭证流调用Microsoft Graph获取邮件的400错误问题

Got it, let's break down why you're hitting that 400 error and fix it up:

核心问题:/me/messages 不支持无用户上下文的调用

The /me endpoint in Microsoft Graph relies on a user context (a logged-in user) to resolve to the current user's mailbox. But when you use the client_credentials flow (the "no user" access you're using), your app is authenticating as itself—there's no associated user context for /me to reference. That's exactly why you're getting a 400 bad request.

解决步骤

1. 修改请求端点为具体用户邮箱

Instead of using /me/messages, you need to target a specific user's mailbox directly using their user principal name (UPN, usually their email address) or Azure AD user ID. Update your url2 line to:

var url2 = "https://graph.microsoft.com/v1.0/users/your-target-user@yourdomain.com/messages";

Replace your-target-user@yourdomain.com with the actual email address of the mailbox you want to access.

2. 确认应用权限配置正确

Even though your JWT shows Mail.Read and Mail.ReadWrite roles, double-check these details in your Azure AD app registration:

  • You've added Application permissions (not Delegated permissions) for Mail.Read/Mail.ReadWrite (the client_credentials flow uses app-level permissions).
  • A global administrator or Exchange administrator has granted admin consent for these permissions. Without admin consent, your app can't access any mailboxes via app-level permissions.

修改后的关键代码片段

// ... 前面获取token的代码保持不变 ...

web = new WebClient();
web.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + data.access_token);
// 替换成目标用户的邮箱地址
var url2 = "https://graph.microsoft.com/v1.0/users/john.doe@contoso.com/messages";
var messages = web.DownloadString(url2);

额外提示

  • If you need to access multiple mailboxes, ensure your app has the necessary broad app-level permissions (like Mail.Read.All for accessing all organization mailboxes) and admin consent is granted for those permissions.
  • You can quickly verify your token's valid permissions by decoding it at jwt.ms (this helps confirm you're using app-level roles instead of delegated ones).

内容的提问来源于stack exchange,提问作者Carol AndorMarten Liebster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:44:48