[Fixed] Microsoft.Graph.Models.ODataErrors.ODataError when trying to get message by Id. Microsoft Graph GraphServiceClient – C#

by
Ali Hasan
.net-4.6 azure-active-directory c# microsoft-graph-mail

Quick Fix: Update the code to use the correct syntax for getting a message by ID using the Microsoft Graph GraphServiceClient in C#.

The Solutions:

Solution 1: Removing .MailFolders["inbox"] from message request and adding TokenCredentialOptions

The issue occurs due to a combination of factors:

  1. Incorrect Graph API endpoint: The code attempts to retrieve a message using the endpoint Users["[email protected]"].MailFolders["inbox"].Messages[message.Id] which is incorrect. The correct endpoint to retrieve a message by ID is Users["[email protected]"].Messages[message.Id].

  2. Missing TokenCredentialOptions: To use ClientSecretCredential with GraphServiceClient, you need to specify the TokenCredentialOptions with the AuthorityHost set to AzurePublicCloud as shown:

var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);

The updated code with the suggested modifications is:

// ... same as before ...

var message = await graphServiceClient.Users["[email protected]"]
    .Messages[message.Id]
    .GetAsync();

// Download the message content
var messageStream = await graphServiceClient.Users["[email protected]"]
    .Messages[message.Id]
    .Content
    .GetAsync();
    
// ... same as before ...

By removing .MailFolders["inbox"] from the message request and adding TokenCredentialOptions, the code will successfully retrieve and download the email message by ID.