Hovi906
Hovi906

Reputation: 35

Sending mail using GraphServiceClient

I wrote a dll using .NET C# that was supposed to send emails using graph API. When I'm using the dll from a console application - everything works as expected: if the user is logged in the mail is sent, and if not - a screen pops up to connect.

But, when I try to use the same dll in WinForms, the program stuck. Any idea why?

This is my code:

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();
}

Upvotes: 1

Views: 1381

Answers (1)

MCattle
MCattle

Reputation: 3167

I'd hazard a guess that you're trying to make the asynchronous method synchronous by calling SendEmailAsync(email).Wait() in your (button click?) event handler, which is causing a WinForms UI thread lock.

The solution is to mark your event handler as async void and await your method in the event handler code.

Upvotes: 1

Related Questions