What is the easiest way with Microsoft Graph to access email messages?

67 Views Asked by At

I am new to Microsoft Graph and I want to use it to read and move email messages. This is my C# code:

static async Task Main(string[] args)
{
    var scopes = new[] { "https://graph.microsoft.com/.default" }
    var tenantId = args[0];
    var clientId = args[1];
    var clientSecret = args[2];
    var options = new TokenCredentialOptions
    {
        AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
    }
    var clientSecretCredential = new ClientSecretCredential(
        tenantId, clientId, clientSecret, options)
    var graphClient = new GraphServiceClient(clientSecretCredential, scopes)
    var messsages = await graphClient.Me.Messages.GetAsync();
    Console.WriteLine(messsages.Value.Count);
    Console.WriteLine("Hello, World!");
}

This is the error message I got:

C:\Users\daan\source\nonrepos\TryMicrosoftGraph\TryOther\Program.cs(26,31): warning CS8602: Dereference of a possibly null reference. [C:\Users\daan\source\nonrepos\TryMicrosoftGraph\TryOther\TryOther.csproj] C:\Users\daan\source\nonrepos\TryMicrosoftGraph\TryOther\Program.cs(26,31): warning CS8602: Dereference of a possibly null reference. [C:\Users\daan\source\nonrepos\TryMicrosoftGraph\TryOther\TryOther.csproj] Unhandled exception. Microsoft.Graph.Models.ODataErrors.ODataError: /me request is only valid with delegated authentication flow.

so the message is:

/me request is only valid with delegated authentication flow.

I am not sure what to do now. Do I really need a "delegated authentication flow". Or is there an easier way to access my messages?

I've seen such errors before on stackoverflow but such posts do not explain how I resolve it in a way it gives me access to the emails.

2

There are 2 best solutions below

0
Martin Godzina On

Your application is a confidential application that requests a token through the client credential flow. This is why the /me path is not functioning as mentioned in the error notification.

Essentially, you still have access to messages from any user within your organization/tenant, but you need to construct a different URL to retrieve those messages.

For instance, you could use this URL to retrieve messages for a user:

# get a message of a user    
GET /users/{id | userPrincipalName}/messages/{id}

Another interesting requests that might help you:

# list all messages of a user
GET /users/{id | userPrincipalName}/messages

# list all users
GET /users
0
Sridevi On

I agree with @MartinGodzina, you need to use /users endpoint with client credentials flow as /me endpoint works only with delegated flows like auth code or interactive.

I registered one Azure AD application and granted API permissions of Application type as below:

enter image description here

Now, you can make use of below modified code by passing either userID or userUPN to read messages using client credentials flow:

using Azure.Identity;
using Microsoft.Graph;
class Program
{
    static async Task Main(string[] args)
    {
        var scopes = new[] { "https://graph.microsoft.com/.default" };
        var tenantId = "tenantId";
        var clientId = "appId";
        var clientSecret = "secret";

        var options = new TokenCredentialOptions
        {
            AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
        };

        var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
        var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
        

        try
        {
            var messages = await graphClient.Users["[email protected]"].Messages.GetAsync();
            Console.WriteLine(messages.Value.Count);
            Console.WriteLine("Hello, World!\n");

            foreach (var message in messages.Value)
            {
                Console.WriteLine($"Subject: {message.Subject}");
            }
        }
        catch (ServiceException serviceException)
        {
            Console.WriteLine(serviceException.Message);
        }
    }
}

Response:

enter image description here

Reference: List messages - Microsoft Graph v1.0