Unable to send Email using Graph API (C# Console) by creating GraphServiceClient through AccessToken as well as ClientCredentialProvider

♀尐吖头ヾ 提交于 2021-02-11 12:50:15

问题


I get the following error Code: OrganizationFromTenantGuidNotFound Message: The tenant for tenant guid 'tenantId' does not exist.

I created a .Net Core console app to send emails using the following 2 functions

I used the following namespaces

using Microsoft.Graph;
using Microsoft.Graph.Auth; //In .Net Core this is in preview only
using Microsoft.Identity.Client;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

Common Email Message to be sent in both the functions

            var message = new Message
            {
                Subject = "Meet for lunch?",
                Body = new ItemBody
                {
                    ContentType = BodyType.Html,
                    Content = "The new cafeteria is open."
                },
                ToRecipients = new List<Recipient>()
            {
                new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = "my email id"
                    }
                }
            },
                CcRecipients = new List<Recipient>()
             {
                 new Recipient
                 {
                     EmailAddress = new EmailAddress
                     {
                         Address = "2nd email id"
                     }
                 }
             }
            };

Scope required in the following functions string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

1st Method

var confidentialClient = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithClientSecret(clientSecret)
                .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}/v2.0"))
                .Build();

            // Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
            var authResult = await confidentialClient
                    .AcquireTokenForClient(scopes)
                    .ExecuteAsync().ConfigureAwait(false);

            var token = authResult.AccessToken;
            // Build the Microsoft Graph client. As the authentication provider, set an async lambda
            // which uses the MSAL client to obtain an app-only access token to Microsoft Graph,
            // and inserts this access token in the Authorization header of each API request. 
            GraphServiceClient graphServiceClient =
                new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
                {
                    // Add the access token in the Authorization header of the API request.
                    requestMessage.Headers.Authorization =
                            new AuthenticationHeaderValue("Bearer", token);
                })
                );

try
            {
                await graphServiceClient.Users["my user guid"]
                      .SendMail(message, false)
                      .Request()
                      .PostAsync();

//I also tried with 
               await graphServiceClient.Me
                      .SendMail(message, false)
                      .Request()
                      .PostAsync();
            }
            catch (Exception ex)
            {


            }

            

2nd Method

 IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
            .Create(clientId)
            .WithTenantId(tenantId)
            .WithClientSecret(clientSecret)
            .Build();

            var authResultDirect = await confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync().ConfigureAwait(false);

//Microsoft.Graph.Auth is required for the following to work
            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
            GraphServiceClient graphClient = new GraphServiceClient(authProvider);


            try
            {
                await graphClient.Users["my user id"]
                        .SendMail(message, false)
                        .Request()
                        .PostAsync();

//I also tried the following
                   await graphClient.Me
                        .SendMail(message, false)
                        .Request()
                        .PostAsync();
            }
            catch (Exception ex)
            {

                
            }

I have given all the required permissions. Some of the permissions are extra and may not be required. I gave the permissions to check if those permissions are the reason why I am getting the error but nothing changed.

I have also checked the token I am getting on jwt.io. I am getting the following roles

 "roles": [
     "Mail.ReadWrite",
     "User.ReadWrite.All",
     "Mail.ReadBasic.All",
     "User.Read.All",
     "Mail.Read",
     "Mail.Send",
     "Mail.ReadBasic"
  ],

I don't see any issue with the code or with the permissions that I have given but I am still missing something which I am unable to figure out. The reason why I say this is because when I tried to get user information by calling the api - https://graph.microsoft.com/v1.0/users, I get the users information as below.

value = [
{
    "businessPhones": [],
    "displayName": "user display name",
    "givenName": "user first name",
    "jobTitle": null,
    "mail": null,
    "mobilePhone": null,
    "officeLocation": null,
    "preferredLanguage": "en",
    "surname": "user last name",
    "userPrincipalName": "user information",
    "id": "user id"
    }
  ]

Any help is appreciated


回答1:


This is because your Azure AD tenant does not have an Exchange online license under the O365 subscription. As a result, your tenant does not have the ability to send Email messages.

If you have an o365 subscription, you'll see it here.

1.

2.

3.




回答2:


@Chauncy Zhou was absolutely right with the solution. But there are a couple of things you need to do if you are an individual because you will not get Office 365 license in your azure account as an individual. I created a Developer.Microsoft.com account and then I used that account to create a new Azure account where I was able to add the license for Office for the Active Directory and that user. Rest of the code is already there and it works fine.



来源:https://stackoverflow.com/questions/64273685/unable-to-send-email-using-graph-api-c-console-by-creating-graphserviceclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!