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

.NET GraphServiceClient发送邮件代码报错及无效果问题求助

使用Microsoft Graph SDK发送邮件的问题

一、高版本SDK的语法错误

我参考VB.NET的SMTP邮件发送示例,改写为C#代码如下:

static async Task SendEmail()
{
    var scopes = new[] { "https://graph.microsoft.com/.default" };

    var tenantId = "";
    var clientId = "";
    var clientSecret = "";

    var options = new TokenCredentialOptions
    {
        AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
    };

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

    var message = new Message
    {
        Subject = "This is the subject line",
        Body = new ItemBody
        {
            ContentType = BodyType.Text,
            Content = "This is the body of the email message."
        },
        ToRecipients = new List<Recipient>
        {
            new Recipient
            {
                EmailAddress = new EmailAddress
                {
                    Address = "user@domain.com"
                }
            }
        }
    };

    await graphClient.Users["myuser@mydomain.com"].SendMail(message, null).Request().PostAsync();
}

运行时出现错误:

Severity    Code    Description Project File    Line    Suppression State
Error   CS1955  Non-invocable member 'UserItemRequestBuilder.SendMail' cannot be used like a method.    MailSend    

错误行:await graphClient.Users["myuser@mydomain.com"].SendMail(message, null).Request().PostAsync();
推测旧版本SDK中该代码有效,但我对.NET和Graph SDK不熟悉,不知道怎么修复。

二、降级到Graph SDK v4后的运行异常

降级到SDK 4版本后,代码无语法错误,但无法正常运行:

using Azure.Identity;
using Microsoft.Graph;

namespace MailSend1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            await SendEmail();
        }

        public static async Task SendEmail()
        {
            var scopes = new[] { "https://graph.microsoft.com/.default" };

            var tenantId = "";
            var clientId = "";
            var clientSecret = "";

            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };

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

            var message = new Message
            {
                Subject = "Just a test!",
                Body = new ItemBody
                {
                    ContentType = BodyType.Text,
                    Content = "Does it work?"
                },
                ToRecipients = new List<Recipient>
                {
                    new Recipient
                    {
                        EmailAddress = new EmailAddress
                        {
                            Address = "someuser@gmail.com"
                        }
                    }
                }
            };

            Console.WriteLine("Mail TO BE sent!");
            bool saveToSentItems = true;

            // 指定发送邮件的租户内用户账号
            await graphClient.Users["test@somedomain.net"].SendMail(message, saveToSentItems).Request().PostAsync();

            Console.WriteLine("Mail sent!");
        }
    }
}

程序运行后,邮件未发送,无错误提示,且第二个Console.WriteLine("Mail sent!");从未执行,请问问题出在哪里?


问题1:高版本SDK语法错误的修复

在Microsoft Graph SDK v5及以上版本中,SendMail的调用方式发生变化,不再使用链式的Request().PostAsync(),而是直接调用PostAsync()方法,且参数需封装为SendMailPostRequestBody对象。修正后代码:

await graphClient.Users["myuser@mydomain.com"].SendMail.PostAsync(new SendMailPostRequestBody
{
    Message = message,
    SaveToSentItems = null
});

问题2:SDK v4版本运行无响应的修复

  1. 修正Main方法的异步处理
    你的Main方法是同步方法,直接调用await会导致程序阻塞,需将Main改为异步:
static async Task Main(string[] args)
{
    await SendEmail();
}
  1. 排查权限与配置
  • 确认tenantId、clientId、clientSecret已正确填写,且Azure AD中已为服务主体授予Mail.Send应用权限并完成管理员同意。
  • 确认发送账号test@somedomain.net存在于你的租户中,服务主体拥有代表该账号发信的权限。
  1. 添加异常捕获排查错误
    在SendEmail方法中添加异常捕获,定位潜在问题:
public static async Task SendEmail()
{
    try
    {
        // 原有代码逻辑...
        await graphClient.Users["test@somedomain.net"].SendMail(message, saveToSentItems).Request().PostAsync();
        Console.WriteLine("Mail sent!");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"发送失败:{ex.Message}");
        if (ex.InnerException != null)
        {
            Console.WriteLine($"内部错误:{ex.InnerException.Message}");
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 04:50:01