无法通过 Microsoft Graph API(C# 控制台)发送电子邮件 [英] Unable to send email via Microsoft Graph API (C# Console)

查看:83
本文介绍了无法通过 Microsoft Graph API(C# 控制台)发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按照这 2 个链接创建了一个控制台应用程序,用于使用 Graph API 发送电子邮件:

我确保提供客户端 ID、租户 ID、客户端机密.

但是,我在运行控制台时看到此错误:

我错过了什么?

这是我从 Microsoft Graph 尝试的代码API 无法发送电子邮件 C# 控制台

static void Main(string[] args){//Azure AD APPstring clientId = "";string tenantID = "<此处的租户密钥>";string clientSecret = "<此处的客户端机密>";任务callTask​​ = Task.Run(() => SendEmail(clientId,tenantID,clientSecret));//等待它完成callTask​​.Wait();//获取结果var astr = callTask​​;}公共静态异步任务SendEmail(字符串clientId,字符串tenantID,字符串clientSecret){var secretClientApplication = ConfidentialClientApplicationBuilder.Create(clientId).WithTenantId(tenantID).WithClientSecret(clientSecret).建造();var authProvider = new ClientCredentialProvider(confidentialClientApplication);var graphClient = new GraphServiceClient(authProvider);var 消息 = 新消息{Subject = "见面吃午饭吗?",正文 = 新项目正文{ContentType = BodyType.Text,Content =新食堂开张了."},ToRecipients = new List(){新收件人{电子邮件地址 = 新电子邮件地址{地址 = "myToEmail@gmail.com";}}},CcRecipients = new List(){新收件人{电子邮件地址 = 新电子邮件地址{地址 = myCCEmail@gmail.com"}}}};var saveToSentItems = true;等待 graphClient.Me.SendMail(消息,saveToSentItems).要求().PostAsync();返回图客户端;}

解决方案

根据您生成 confidentialClientApplication 的代码,您正在使用 客户端凭据提供程序.

但是您发送电子邮件的方式是:

await graphClient.Me.SendMail(消息,saveToSentItems).要求().PostAsync()

实际上是在调用 https://graph.microsoft.com/v1.0/me/sendMail.

但客户端凭据流不支持 /me 端点.您应该调用 https://graph.microsoft.com/v1.0/users/{id |在这种情况下,userPrincipalName}/sendMail 端点.

所以代码应该是:

await graphClient.Users[{id or userPrincipalName}"].SendMail(消息,saveToSentItems).要求().PostAsync();

或者,如果您想使用 /me/sendMail,请选择 授权码提供者,你应该在这里实现交互式登录.

您可以了解 授权代码流客户端凭据流程.

I followed these 2 links to create a console app for sending emails using Graph API:

https://docs.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0&tabs=csharp

Microsoft Graph API unable to Send Email C# Console

I have added & granted the required permissions in Azure AD app:

I made sure to provide the client id, tenant id, client secret.

However, I see this error on running the console:

What am I missing?

Here is the code I tried from Microsoft Graph API unable to Send Email C# Console

static void Main(string[] args)
    {
        // Azure AD APP
        string clientId = "<client Key Here>";
        string tenantID = "<tenant key here>";
        string clientSecret = "<client secret here>";

        Task<GraphServiceClient> callTask = Task.Run(() => SendEmail(clientId, tenantID, clientSecret));
        // Wait for it to finish
        callTask.Wait();
        // Get the result
        var astr = callTask;
    }

    public static async Task<GraphServiceClient> SendEmail(string clientId, string tenantID, string clientSecret)
    {

        var confidentialClientApplication = ConfidentialClientApplicationBuilder
            .Create(clientId)
            .WithTenantId(tenantID)
            .WithClientSecret(clientSecret)
            .Build();

        var authProvider = new ClientCredentialProvider(confidentialClientApplication);       

        var graphClient = new GraphServiceClient(authProvider);

        var message = new Message
        {
            Subject = "Meet for lunch?",
            Body = new ItemBody
            {
                ContentType = BodyType.Text,
                Content = "The new cafeteria is open."
            },
            ToRecipients = new List<Recipient>()
            {
                new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = "myToEmail@gmail.com"
                    }
                }
            },
            CcRecipients = new List<Recipient>()
            {
                new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = "myCCEmail@gmail.com"
                    }
                }
            }
        };

        var saveToSentItems = true;

          await graphClient.Me
            .SendMail(message, saveToSentItems)
            .Request()
            .PostAsync();

        return graphClient;

    }

解决方案

Based on your code which generates the confidentialClientApplication, you are using Client credentials provider.

But the way you send the email is:

await graphClient.Me
.SendMail(message, saveToSentItems)
.Request()
.PostAsync()

It is calling https://graph.microsoft.com/v1.0/me/sendMail in fact.

But Client credentials flow doesn't support /me endpoint. You should call https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}/sendMail endpoint in this case.

So the code should be:

await graphClient.Users["{id or userPrincipalName}"]
    .SendMail(message, saveToSentItems)
    .Request()
    .PostAsync();

Or if you want to use /me/sendMail, choose Authorization code provider, where you should implement interactive login.

You can learn about the scenarios and differences between authorization code flow and client credentials flow.

这篇关于无法通过 Microsoft Graph API(C# 控制台)发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆