When I try to download an email from a shared mailbox using the GraphServiceClient I keep getting Exception of type 'Microsoft.Graph.Models.ODataErrors.ODataError' was thrown. The OData request is not supported. I've googled the issue and haven't gotten a usable solution.
Originally started with app permission Mail.ReadWrite. From there added Mail.Read, Mail.ReadBasic,Mail.ReadBasic.All to see if anything would work. Below is a sample of the code that I'm using.
ClientSecretCredential? _clientSecretCredential = new ClientSecretCredential(_settings.TenantId, _settings.ClientId, _settings.ClientSecret);
var graphServiceClient = new GraphServiceClient(_clientSecretCredential,new[] { "https://graph.microsoft.com/.default" });
var messages = await graphServiceClient.Users["[email protected]"].MailFolders["inbox"].Messages.GetAsync();
//messages returns 3 emails
foreach (var message in messages.Value)
{
//this throws the error---------------------------------------
var messageStream = await graphServiceClient
.Users["[email protected]"]
.MailFolders["inbox"]
.Messages[message.Id]
.Content
.GetAsync();
//---------------------------------------------------------------
string path = "File_Path.eml";
using (FileStream fs = new FileStream(path, FileMode.CreateNew))
{
messageStream.CopyTo(fs);
}
}
If there is any gotcha's as far as Azure configurations you can think of that would be appreciated.
Update: As per the answer below, removing .MailFolders["inbox"] from the message request and adding in TokenCredentialOptions fixed the issue.
using Azure.Identity;
using Microsoft.Graph;
using System;
using System.IO;
namespace GraphApp
{
class MSGraph
{
static async Task Main(string[] args)
{
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenant_Id";
var clientId = "client_Id";
var clientSecret = "client_Secret";
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
try
{
var message = await graphClient.Users["User_UPN"]
.MailFolders["inbox"]
.Messages["message_ID"]
.GetAsync();
var mimeContentStream = await graphClient.Users["User_ID"]
.Messages[message.Id]
.Content
.GetAsync();
using (var fileStream = File.Create("C:\\Users\\xxxxxxx\\Desktop\\web1\\lastemail.eml"))
{
mimeContentStream.Seek(0, SeekOrigin.Begin);
await mimeContentStream.CopyToAsync(fileStream);
}
Console.WriteLine("Email message downloaded successfully.");
}
catch (ServiceException ex)
{
Console.WriteLine($"Error accessing the Graph API: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
}
References: