【发布时间】:2019-04-08 10:50:21
【问题描述】:
我正在尝试创建允许我代表特定用户发送电子邮件的 Windows 服务。
Graph Client 的最新版本允许使用WithMaxRetry 指定重试。
不幸的是,在创建ConfidentialClientApplication 时,没有任何好的示例显示“最佳实践”。
目前,我使用以下代码发送电子邮件而不要求登录名和密码:
const string clientId = "foo...99a0";
const string clientSecret = "#6A...cx#$a";
const string tenant = "1c...7";
const string azureAdInstance = "https://login.microsoftonline.com/{0}";
var authority = string.Format(CultureInfo.InvariantCulture, azureAdInstance, tenant);
string[] scopes = { "https://graph.microsoft.com/.default" };
var clientCredentials = new ClientCredential(clientSecret);
var confidentialClientApplication =
new ConfidentialClientApplication(
clientId,
authority,
"https://daemon",
clientCredentials,
null,
new TokenCache());
var graphClient =
new GraphServiceClient("https://graph.microsoft.com/v1.0",
new DelegateAuthenticationProvider(
async(requestMessage) =>
{
var result = await confidentialClientApplication
.AcquireTokenForClientAsync(scopes);
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("bearer", result.AccessToken);
}));
var recipients = new List<Recipient>
{
new Recipient
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "test@example.com"
}
}
};
var email = new Message
{
Body = new ItemBody
{
Content = "Works fine!",
ContentType = BodyType.Html,
},
Subject = "Test",
ToRecipients = recipients
};
await graphClient
.Users["sender@example.onmicrosoft.com"]
.SendMail(email, true)
.Request()
.PostAsync();
但我不知道如何根据 Request Context With Middleware Options 的最近更改来创建 ConfidentialClientApplication。
因为我找不到最新的示例,我的问题是,我应该如何创建 GraphServiceClient 才能从 Windows 服务发送电子邮件?
这是上面 PR 的代码:
HttpProvider httpProvider = new HttpProvider();
var graphClient = new GraphServiceClient(appOnlyProvider, httpProvider);
graphClient.PerRequestAuthProvider = () => CreateDelegatedProvider();
var me = await graphClient.Me.Request()
.WithScopes(string[] { "User.Read" }) // adds auth scopes
.WithMaxRetry(5) // specifies maximum number of retries
.WithPerRequestAuthProvider()
.GetAsync();
我应该如何根据我的要求采用它? 我是 Graph 新手,所以我想避免错误的代码。
【问题讨论】:
标签: c# microsoft-graph-api microsoft-graph-sdks microsoft-graph-mail