gpt4 book ai didi

c# - 无法通过 Microsoft Graph API(C# 控制台)发送电子邮件

转载 作者:行者123 更新时间:2023-12-04 14:11:07 25 4
gpt4 key购买 nike

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

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

Microsoft Graph API unable to Send Email C# Console

我已在 Azure AD 应用中添加并授予所需的权限:

enter image description here

我确保提供了客户端 ID、租户 ID、客户端密码。

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

enter image description here

我错过了什么?

这是我从 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;

}

最佳答案

根据生成 confidentialClientApplication 的代码,您正在使用 Client credentials provider .

但是你发送邮件的方式是:

await graphClient.Me
.SendMail(message, saveToSentItems)
.Request()
.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(message, saveToSentItems)
.Request()
.PostAsync();

或者如果你想使用/me/sendMail,选择Authorization code provider ,您应该在其中实现交互式登录。

您可以了解authorization code flow之间的场景和差异和 client credentials flow .

关于c# - 无法通过 Microsoft Graph API(C# 控制台)发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64270365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com