Search code examples
c#.netemailmicrosoft-graph-sdks

Retrieving Sent Email ID from Microsoft Graph API


I'm currently using the Microsoft Graph API to send emails in a .NET application. My current code to send an email looks like this:

await client.Users[model.From]
            .SendMail(message, true)
            .Request()
            .PostAsync(cancellationToken)
            .ConfigureAwait(false);

This successfully sends the email, but the SendMail function doesn't return any direct information about the sent email, and specifically, it doesn't give me the Id of the sent email. I need to keep track of this ID for later use in my application.

I've looked into fetching the most recent email from the 'Sent Items' folder after the SendMail function call, but I'm worried about the reliability of this approach:

var sentItems = await client.Users[model.From]
                            .MailFolders["SentItems"]
                            .Messages
                            .Request()
                            .Top(1)
                            .OrderBy("receivedDateTime desc")
                            .GetAsync();

string messageId = sentItems.CurrentPage.FirstOrDefault()?.Id;

I also thought about manually setting the email id, but from my understanding, this field is ignored and assigned automatically from the server side.

Is there any other way to retrieve the ID of the sent email directly from the SendMail operation?


Solution

  • Instead of using SendMail you can create a Draft message, get the ID and then Send it. You'll probably also want to make the message ID imutable.

    https://learn.microsoft.com/en-us/graph/api/user-post-messages?view=graph-rest-1.0&tabs=http https://learn.microsoft.com/en-us/graph/api/message-send?view=graph-rest-1.0&tabs=http https://learn.microsoft.com/en-us/graph/outlook-immutable-id