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. Azure API Permissions

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

2

There are 2 answers

3
Chauncy Zhou On BEST ANSWER

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.

enter image description here

2.

enter image description here

3.

enter image description here

0
Jatinder Singh On

@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.