返回

microsoft graph api-使用GraphServiceClient发送邮件

发布时间:2022-05-21 01:50:17 351

我使用 .NET C# 编写了一个 dll,它应该使用图形 API 发送电子邮件。当我从控制台应用程序使用 dll 时 - 一切都按预期工作:如果用户登录,则发送邮件,如果没有 - 会弹出一个屏幕进行连接。

但是,当我尝试在 WinForms 中使用相同的 dll 时,程序卡住了。知道为什么吗?

这是我的代码:

var options = new PublicClientApplicationOptions {
  ClientId = clientId,
  TenantId = tenantId,
  RedirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient",
};

if (application == null) {
  application = PublicClientApplicationBuilder.CreateWithApplicationOptions(options).WithAuthority(AzureCloudInstance.AzurePublic, ClientSecretOrTenantId).Build();
}

string token = "";

GraphServiceClient graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider(async(requestMessage) =>{
  token = await GetToken();
  requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
}));

Recipient recipient = new Recipient();
recipient.EmailAddress = new EmailAddress();
recipient.EmailAddress.Address = toAddress;

List < Recipient > recipients = new List < Recipient > ();
recipients.Add(recipient);

var message = new Message {
  Subject = subject,
  Body = new ItemBody {
    ContentType = isHtml ? BodyType.Html: BodyType.Text,
    Content = bodyText,
  },
  ToRecipients = recipients,
};

try {
  await graphServiceClient.Me.SendMail(message, false).Request().PostAsync(); // get stuck here
} catch(ServiceException) {
  graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider(async(requestMessage) =>{
    token = await GetToken();
    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
  }));
  await graphServiceClient.Me.SendMail(message, false).Request().PostAsync();
}
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像