msgraph-sdk-dotnet icon indicating copy to clipboard operation
msgraph-sdk-dotnet copied to clipboard

Confusing / misleading error when reusing Message object

Open RichardD2 opened this issue 4 months ago • 0 comments

Whilst attempting to implement a custom "retry" policy for sending email, I encountered a misleading exception which I've just spent hours trying to diagnose.

The mistake I made was using the same Message object in multiple API calls:

Message message = new() { ... };

var delay = TimeSpan.FromMilliseconds(500);
for (int attempt = 0; attempt < 5; attempt++)
{
    try
    {
        await mailbox.SendMail
            .PostAsync(new() { Message = message, SaveToSentItems = storeInSentItems, }, PreferImmutableIds, cancellationToken)
            .ConfigureAwait(false);
        
        break;
    }
    catch (Exception ex) when (attempt < 4)
    {
        Logger.LogInformation("Message sending failed; pausing to try again. (Attempt {attempt})\n{Error}", attempt, ex);
        await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
        delay = TimeSpan.FromMilliseconds(delay.TotalMilliseconds * 1.5);
    }
}

On the first attempt, the exception was "missing required property" - turns out I need to add a Name to every FileAttachment, including inline images which don't actually have a name.

But from the second attempt onwards, and the exception that finally escaped from the loop, the error was:

At least one recipient is not valid., A message can't be sent because it contains no recipients.

This lead me down a rabbit-hole of triple-checking that I had added at least one recipient; that the recipient was valid; that there were no issues sending email to the recipient; etc.

The limited Google search results for this error message bring up one person who was using the wrong endpoint, and several posts where the OP never responded to requests for more information and were therefore closed. Nothing I could find pointed to the underlying problem: using the same Message object - or, more specifically, the same Recipient object - more than once does not work.

(I've also found that using the same Recipient object for the From address and the ReplyTo list doesn't work, presumably for the same reason.)

Assuming there's some fundamental reason why these objects can't be used more than once, it would be nice if this unsupported use of the library could be detected, and a more specific error generated pointing the developer to the appropriate documentation.

RichardD2 avatar Mar 07 '24 18:03 RichardD2