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

.NET 7下C#控制台应用调用Microsoft Graph发邮件遇问题求助

问题描述

我在.NET 7环境下使用C#控制台应用,参考Microsoft Graph邮件发送示例,采用Client Credentials Provider认证方式实现邮件发送功能。已配置Azure应用注册的API权限,但运行代码时出现错误,尝试将graphClient.Me.SendMail改为graphClient.Users["<邮箱>"].SendMail后问题仍存在。

现有代码

Program.cs

namespace EmailGraphTesting
{
    public class Program
    {
        static async Task Main(string[] args)
        {
            await SendEmail.SendEmailAsync();
        }
    }
}

SendEmail类

using Microsoft.Graph;
using Azure.Identity;
using Microsoft.Graph.Models;
using Microsoft.Graph.Me.SendMail; 

namespace EmailGraphTesting
{
    public class SendEmail
    {
        public static string tenantId = "<tenant Id>";
        public static string clientId = "<client Id>";
        public static string clientSecret = "<client secret>";
        public static string[] scopes = new[] { "https://graph.microsoft.com/.default" };

        public static async Task SendEmailAsync()
        {
            var options = new ClientSecretCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
            };

            var clientSecretCredential = new ClientSecretCredential(
                tenantId, clientId, clientSecret, options);

            var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

            var requestBody = new SendMailPostRequestBody
            {
                Message = new Message
                {
                    Subject = "Outbox Test",
                    Body = new ItemBody
                    {
                        ContentType = BodyType.Text,
                        Content = "1st attempt"
                    },
                    ToRecipients = new List<Recipient>()
                    {
                        new Recipient
                        {
                            EmailAddress = new EmailAddress
                            {
                                Address = "<receiverEmail here>"
                            }
                        }
                    },
                },
            };
            await graphClient.Me.SendMail.PostAsync(requestBody);
        }
    }
}
问题排查与解决方案

1. 核心问题:Client Credentials模式禁用Me端点

Client Credentials是应用级权限认证,代表应用本身身份,未绑定具体用户,因此graphClient.Me必然报错,必须指定租户内具体用户的ID或邮箱来发送邮件。

2. 验证Azure应用权限配置

  • 确认已添加应用权限(而非委派权限)Mail.Send,且状态为已授予管理员同意。仅添加权限未完成管理员授权会导致403权限错误。
  • 检查权限范围是否覆盖目标用户,部分租户可能对应用权限的用户范围做了限制。

3. 代码修正要点

(1)规范指定发送用户

确保Users参数使用租户内有效用户的UPN(通常是邮箱)或Azure AD用户ID,示例:

await graphClient.Users["sender@yourtenant.com"].SendMail.PostAsync(requestBody);

(2)完善请求体配置

添加SaveToSentItems = true,确保邮件保存到发件人的已发送文件夹(可选但符合常规需求):

var requestBody = new SendMailPostRequestBody
{
    Message = new Message
    {
        Subject = "Outbox Test",
        Body = new ItemBody
        {
            ContentType = BodyType.Text,
            Content = "1st attempt"
        },
        ToRecipients = new List<Recipient>()
        {
            new Recipient
            {
                EmailAddress = new EmailAddress
                {
                    Address = "<receiverEmail here>"
                }
            }
        },
    },
    SaveToSentItems = true
};

(3)捕获详细错误信息

添加异常捕获,获取Graph API返回的具体错误详情,快速定位问题:

try
{
    await graphClient.Users["sender@yourtenant.com"].SendMail.PostAsync(requestBody);
    Console.WriteLine("邮件发送成功");
}
catch (ServiceException ex)
{
    Console.WriteLine($"Graph API错误: {ex.Message}");
    Console.WriteLine($"错误代码: {ex.Error.Code}");
    Console.WriteLine($"错误详情: {ex.ResponseBody}");
}

4. 常见错误排查方向

  • 权限未授权:应用权限必须由租户管理员完成“授予管理员同意”操作,否则权限不生效。
  • 用户参数错误:Users参数不能使用外部邮箱,必须是当前租户内的有效用户。
  • 租户策略限制:部分租户可能通过Exchange Online策略限制应用代表用户发送邮件,需联系租户管理员确认。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:20:00