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

使用MS Graph委托权限及服务账户发邮件遇字典键缺失错误求助

问题:Microsoft Graph SDK v4 委托权限+服务账户发邮件时出现字典键不存在错误

场景与代码

使用Microsoft Graph SDK 4版本,通过委托权限结合服务账户发送邮件,代码如下:

IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder.Create("ClientId").WithTenantId("TenantId").Build();
UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication);
GraphServiceClient _graphClient = new GraphServiceClient(authProvider);
await _graphClient.Me.SendMail(message, true).Request().WithUsernamePassword("ServiceAccountUser", "ServiceAccountUserPassword").PostAsync().ConfigureAwait(false);

已添加对应权限(见附图),执行代码时触发错误:

The given key 'Microsoft.Graph.AuthenticationHandlerOption' was not present in the dictionary.


问题分析

这个错误的核心原因是身份验证配置冲突:你已经通过UsernamePasswordProvider为GraphServiceClient全局配置了用户名密码验证逻辑,但又在单个请求级别调用WithUsernamePassword重复传入凭证,导致SDK内部处理时无法找到对应的配置键,引发字典查找异常。


解决方案

1. 移除请求级别的重复凭证配置

直接删除Request()后的.WithUsernamePassword("ServiceAccountUser", "ServiceAccountUserPassword")调用,修改后的代码如下:

IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder.Create("ClientId").WithTenantId("TenantId").Build();
UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication);
GraphServiceClient _graphClient = new GraphServiceClient(authProvider);

await _graphClient.Me.SendMail(message, true)
                  .Request()
                  .PostAsync()
                  .ConfigureAwait(false);

2. 验证权限配置

确认Azure AD应用注册中已添加委托权限Mail.Send,且已完成管理员同意(针对租户范围应用),同时服务账户拥有可发送邮件的邮箱权限。

3. 排查SDK版本问题

确保使用的是Microsoft Graph SDK v4的稳定版本,若版本过旧可能存在此类已知bug,建议更新至最新的v4.x版本。


内容的提问来源于stack exchange,提问作者Akhil Tyagi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 09:52:12