我按照这 2 个链接创建了一个控制台应用程序,用于使用 Graph API 发送电子邮件:
Microsoft Graph API 无法发送电子邮件 C# 控制台 https://stackoverflow.com/questions/57411274/microsoft-graph-api-unable-to-send-email-c-sharp-console
我已在 Azure AD 应用程序中添加并授予了所需的权限:
我确保提供了客户端 ID、租户 ID、客户端密码。
但是,我在运行控制台时看到此错误:
我缺少什么?
这是我尝试过的代码Microsoft Graph API 无法发送电子邮件 C# 控制台 https://stackoverflow.com/questions/57411274/microsoft-graph-api-unable-to-send-email-c-sharp-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 = "[email protected] /cdn-cgi/l/email-protection"
}
}
},
CcRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "[email protected] /cdn-cgi/l/email-protection"
}
}
}
};
var saveToSentItems = true;
await graphClient.Me
.SendMail(message, saveToSentItems)
.Request()
.PostAsync();
return graphClient;
}