【问题标题】:Sending mail using GraphServiceClient使用 GraphServiceClient 发送邮件
【发布时间】:2022-10-05 08:59:23
【问题描述】:

我使用 .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();
}

【问题讨论】:

    标签: microsoft-graph-api


    【解决方案1】:

    我猜测您正试图通过在您的(按钮单击?)事件处理程序中调用 SendEmailAsync(email).Wait() 来使异步方法同步,这会导致 WinForms UI 线程锁定。

    解决方案是在事件处理程序代码中将您的事件处理程序标记为async voidawait 您的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 2012-04-27
      • 2019-07-14
      • 2016-02-07
      相关资源
      最近更新 更多