方案:控制台应用程序需要从定义的邮箱发送电子邮件。 Azure中的所有设置均已完成,应用程序可以访问,并且在Postman中都可以正常工作。
问题是如何使用Microsoft库(特别是使用GraphServiceClient
)。
注意:示例未显示消息正文,因为它与问题无关。
原始请求
POST https://graph.microsoft.com/v1.0/users/<email-address>/sendMail
.NET代码
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithAuthority(AzureCloudInstance.AzurePublic, tenantId)
.WithClientSecret(secret)
.Build();
ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
await graphClient.Me
.SendMail(message, saveToSentItems)
.Request()
.PostAsync();
答案 0 :(得分:1)
我已经在c#.NET中完成了此操作-这是一些代码,这些代码已经过动态重构/简化(因此无法保证),以仅显示您的需求。显然,您需要用自己的值替换魔术字符串。
var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider(async request =>
{
var authContext = new AuthenticationContext("https://login.microsoftonline.com/GUID");
var credential = new ClientCredential("GUID", "P@55w0rd");
var authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credential);
request.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
}));
var user = graphServiceClient.Users["from@example.com"];
var message = GetMailMessage(); // not relevant to question
await user.SendMail(message).Request().PostAsync(new CancellationTokenSource(new TimeSpan(0, 0, 30)).Token);