Microsoft Graph C# enumate a specific mailbox messages?

WardH 61 Reputation points
2021-08-12T14:07:49.207+00:00

Hi,

I am trying to write a .NET Core App using Microsoft Graph to enumare users from and read a specific mailbox from Office 365.

The exception in my code I get is:

Microsoft.Graph.ServiceException
HResult=0x80131500
Message=Code: generalException
Message: An error occurred sending the request.

Source=Microsoft.Graph.Core
StackTrace:
at Microsoft.Graph.HttpProvider.<SendRequestAsync>d__19.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Microsoft.Graph.HttpProvider.<SendAsync>d__18.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.Graph.BaseRequest.<SendRequestAsync>d__40.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Microsoft.Graph.BaseRequest.<SendAsync>d__341.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Microsoft.Graph.GraphServiceUsersCollectionRequest.<GetAsync>d__3.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at Graph_Email_Test1_Issue.Program.<Main>d__0.MoveNext() in E:\Data\Ward\Documents\Visual_Studio_Projects\Graph_Email_Test1_Issue\Graph_Email_Test1_Issue\Program.cs:line 59

This exception was originally thrown at this call stack:
[External Code]

Inner Exception 1:
AuthenticationFailedException: ClientSecretCredential authentication failed: AADSTS1002012: The provided value for scope https://graph.microsoft.com/Directory.Read.All https://graph.microsoft.com/Domain.Read.All https://graph.microsoft.com/Mail.Read https://graph.microsoft.com/User.Read.All is not valid. Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).
Trace ID: c18e06ac-ba5a-40d6-a85a-c62c4556fa02
Correlation ID: 56fd4ab0-3549-4719-8e3d-c0e67af93344
Timestamp: 2021-08-12 13:46:38Z

Inner Exception 2:
MsalServiceException: AADSTS1002012: The provided value for scope https://graph.microsoft.com/Directory.Read.All https://graph.microsoft.com/Domain.Read.All https://graph.microsoft.com/Mail.Read https://graph.microsoft.com/User.Read.All is not valid. Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).
Trace ID: c18e06ac-ba5a-40d6-a85a-c62c4556fa02
Correlation ID: 56fd4ab0-3549-4719-8e3d-c0e67af93344
Timestamp: 2021-08-12 13:46:38Z

My questions are:

  1. How can I fix the code to get rid of the exception?
  2. How can I change the code so I can enumate a specific mailbox?

Here is the code that follows (AAA, BBB, CCC) are not the real values of course:

using Azure.Identity;  
using Microsoft.Graph;  
using System;  
using System.Linq;  
using System.Threading.Tasks;  
  
// Install-Package Microsoft.Graph  
// Install-Package Microsoft.Graph.Auth -IncludePrerelease  
  
// App Permissions in Azure AD Console (Have also granted admin consent):  
  
// https://graph.microsoft.com/Directory.Read.All  
// https://graph.microsoft.com/Domain.Read.All  
// https://graph.microsoft.com/Mail.Read  
// https://graph.microsoft.com/User.Read.All  
  
  
namespace Graph_Email_Test1_Issue  
{  
    class Program  
    {  
        static async Task Main(string[] args)  
        {  
            //var scopes = new[] { "User.Read.All" };  
  
            var scopes = new string[] { "https://graph.microsoft.com/Directory.Read.All",  
                                        "https://graph.microsoft.com/Domain.Read.All",  
                                        "https://graph.microsoft.com/Mail.Read",  
                                        "https://graph.microsoft.com/User.Read.All"};  
  
  
            // Multi-tenant apps can use "common",  
            // single-tenant apps must use the tenant ID from the Azure portal  
            var tenantId = "AAA";  
  
            // Values from app registration  
            var clientId = "BBB";  
            var clientSecret = "CCC";  
  
            var options = new TokenCredentialOptions  
            {  
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud  
            };  
  
            // https://learn.microsoft.com/dotnet/api/azure.identity.clientsecretcredential  
            var clientSecretCredential = new ClientSecretCredential(  
                tenantId, clientId, clientSecret, options);  
  
            var graphClient = new GraphServiceClient(clientSecretCredential, scopes);  
  
            //var user = await graphClient.Me  
            //    .Request()  
            //    .GetAsync();  
  
  
            // var user = await graphClient.Me.Request().GetAsync();  
  
  
            var users = await graphClient.Users.Request().GetAsync();   // Generates exception below.  
  
            var user = users.First(); //get the first user  
  
  
            //var messages = await graphClient.Me.Messages  
            //    .Request()  
            //    .GetAsync();  
        }  
    }  
}  
  
  
  
  
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
11,450 questions
0 comments No comments
{count} votes

Accepted answer
  1. Glen Scales 4,431 Reputation points
    2021-08-12T23:33:21.53+00:00

    for the Scope you can just use

    var scopes = new string[] {"https://graph.microsoft.com/.default"};  
    

    In your Application registration its important that you assigned Application permissions not Delegate Permissions https://learn.microsoft.com/en-us/graph/permissions-reference and they need to be consented to (by and Admin) in the tenant

    To get Messages from a particular users mailbox you just need

    var messages = await graphClient.Users["user@tenant.onmicrosoft.com"].Messages  
    

    The /me endpoint won't work when using a Service Principal (Client_Credentials Flow)

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful