I have a need to send multiple emails using Microsoft Graph from Windows Service.
I'm using Microsoft.Graph
NuGet package.
I'm creating GraphServiceClient
and sending mail like so:
IGraphServiceClient graphClient = new GraphServiceClient("https://graph.microsoft.com/v1.0", authenticationProvider);
var email = new Message
{
Body = new ItemBody
{
Content = "Works fine!",
ContentType = BodyType.Html,
},
Subject = "Test",
ToRecipients = recipientList
};
await graphClient.Users["test@example.onmicrosoft.com"].SendMail(email, true).Request().WithMaxRetry(5).PostAsync();
When I send emails one-by-one:
for (var j = 0; j < 20; j++)
{
await graphClient.Users["test@example.onmicrosoft.com"].SendMail(email, true).Request().WithMaxRetry(5).PostAsync();
progressBar1.PerformStep();
}
everything works fine, but when I use Parallel.For
:
var res = Parallel.For(0, 20, async (i, state) =>
{
var email = new Message
{
Body = new ItemBody
{
Content = "Works fine!",
ContentType = BodyType.Html,
},
Subject = "Test",
ToRecipients = recipientList
};
await graphClient.Users["test@example.onmicrosoft.com"].SendMail(email, true).Request().WithMaxRetry(5).PostAsync();
});
i get errors, because I get Too Many Requests (429) and then Unsupported Media Type (415).
This is the error code:
Code: RequestBodyRead Message: A missing or empty content type header was found when trying to read a message. The content type header is required.
This is how it looks in Fiddler:
My question is: can I use and how I should use Graph with Parallel.For
to avoid this kind of errors. I'm already setting WithMaxRetry(5)
for each request.
I'm aware of usage limits, but I thought WithMaxRetry(5)
will help.