How to read User's email message from Extermal Azure AD using Graph SDK in C#

abhishek appu 41 Reputation points
2022-11-25T07:12:21.6+00:00

class Program
{
static void Main(string[] args)
{
ReadEmail();
}
public static async void ReadEmail()
{
var scopes = new[] { "https://graph.microsoft.com/v1.0/dashmagiq@vidyatech.in/mailFolders/Inbox/messages?$filter=isRead" };
var tenantId = ConfigurationManager.AppSettings["tenantId"];
var appId = ConfigurationManager.AppSettings["appId"];
var clientSecret = ConfigurationManager.AppSettings["clientSecret"];
var clientSecretCredential = new ClientSecretCredential(
tenantId, appId, clientSecret);
GraphServiceClient graphClient = new GraphServiceClient(clientSecretCredential, scopes);
//var inboxMessages = graphClient
// .Users["dashmagiq@vidyatech.in"]
// .MailFolders["inbox"]
// .Messages
// .Request()
// .Expand("attachments")
// .Top(20)
// .GetAsync();
var inboxMessages = await graphClient.Me
//./Users["dashmagiq@vidyatech.in"]/
.MailFolders["inbox"]
.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.
10,649 questions
{count} votes

Accepted answer
  1. Rob Windsor 1,956 Reputation points
    2022-11-25T12:06:24.32+00:00

    The value for the variable scopes is wrong. You need to set this to the Microsoft Graph permission scopes necessary to read email messages from all mailboxes. Because you're using application permissions, this permission request should be made in the Azure Portal rather in your code.

    First, request the Mail.Read application permission.

    264217-image.png

    Then grant that permission.

    264218-image.png

    Then set the value of scopes as shown below. This tells Microsoft Graph to use the permissions configured in the Azure Portal.

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

    Here are links to a couple Microsoft Learn training paths that can give you some more foundational training on how to use Microsoft Graph.

    Microsoft Graph Fundamentals

    MS-600: Build apps with Microsoft Graph - Associate


0 additional answers

Sort by: Most helpful