Unable to Get User Mail Folders in C# code but getting in Graph Explorer

Viewed 29

My Goal is to read any user office 365 outlook (email) messages with attachments and do delete specific message by applying filters.

I had created application in Azure AD, provided Graph Application Permissions with proper scopes and granted admin consents. Reference screenshot shown below

enter image description here

I am able to get mail messages using Graph Explorer with API https://graph.microsoft.com/v1.0/users/testuser@outlook.com/messages

I had cloned github sample and enhancing to list all message, get mail attachments etc all kind of mail related things.

I am able to get list of users from Azure AD but failed to get messages even if i apply specific user email.

Enhanced Code:

 private static async Task CallMSGraphUsingGraphSDK(IConfidentialClientApplication app, string[] scopes)
        {
            // Prepare an authenticated MS Graph SDK client
            GraphServiceClient graphServiceClient = GetAuthenticatedGraphClient(app, scopes);

            try
            {
                  string name = "ANYUSER@outlook.com";

               //Listing All Users
                var users = await graphServiceClient.Users.Request().GetAsync();

                foreach (var user in users)
                {
                    Console.WriteLine($"{user.Id}, {user.GivenName} {user.Surname}, {user.MemberOf}, {user.UserPrincipalName}, {user.Mail}");
                }
                 
                //Trying to get any user outlook messages.
                var userdetails = await graphServiceClient.Users.Request().Filter($"mail eq '{name}'").GetAsync();
                Console.WriteLine($"Hello, {userdetails.FirstOrDefault().DisplayName}");

                // Get the first user's mail folders
                var mailFolders = await graphServiceClient
                    .Users[userdetails[0].Id].Messages.Request().GetAsync();

                var inboxMail = await graphServiceClient.Users[userdetails.FirstOrDefault().Id].MailFolders.Inbox.Messages.Request().GetAsync();
                foreach (var mail in inboxMail.CurrentPage.ToList())
                {
                    Console.WriteLine("From: {0}\nSubject: {1}\nBody:\n{2}\n--------------------\n", mail.From.EmailAddress.Address, mail.Subject, mail.BodyPreview);
                }
            }
            catch (ServiceException e)
            {
                Console.WriteLine("Exception Caught: " + $"{e}");
            }

        }

I am using Graph SDK .

enter image description here

enter image description here

What am I doing wrong?

0 Answers
Related