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["[email protected]"].SendMail(email, true).Request().WithMaxRetry(5).PostAsync();
When I send emails one-by-one:
for (var j = 0; j < 20; j++)
{
await graphClient.Users["[email protected]"].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["[email protected]"].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.
The reason why you saw this is because of the missing content type header. It wasn't being cloned when we cloned the httprequestmessage. This has been fixed and will be in the next release of the client. With regards to parallel threads, we plan on implementing a resource based shared retry queue so that we use a single retry scheme across multiple requests that target the same resource (and the same throttling policy).