通过AccessToken和ClientCredentialProvider创建GraphServiceClient,因此无法使用Graph APIC#控制台发送电子邮件

问题描述

我收到以下错误 代码:OrganizationFromTenantGuidNotFound 消息:承租人guid'tenantId'的承租人不存在。

我创建了一个.Net Core控制台应用程序,以使用以下2个功能发送电子邮件

我使用了以下命名空间

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

将在两个功能中发送的公用电子邮件消息

            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"
                     }
                 }
             }
            };

以下功能所需的范围 字符串[]范围=新字符串[] {“ https://graph.microsoft.com/.default”};

第一种方法

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)
            {


            }

            

第二种方法

 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)
            {

                
            }

我已授予所有必需的权限。一些权限是额外的,可能不需要。我授予了权限,以检查这些权限是否是我收到错误但没有任何更改的原因。

Azure API Permissions

我还检查了我在jwt.io上获得的令牌。我要担任以下角色

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

我看不到代码或授予的权限有任何问题,但仍然缺少我无法弄清的内容。之所以这样说,是因为当我尝试通过调用api- https://graph.microsoft.com/v1.0/users 获取用户信息时,会得到如下的用户信息。

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"
    }
  ]

感谢您的帮助

解决方法

这是因为您的Azure AD租户在O365订阅下没有Exchange联机许可证。 因此,您的租户无法发送电子邮件。

如果您有o365订阅,您将在这里看到它。

1。

enter image description here

2。

enter image description here

3。

enter image description here

,

@Chauncy Zhou绝对正确。 但是,如果您是个人,则需要做几件事,因为您将不会在Azure帐户中以个人身份获得Office 365许可证。 我创建了一个Developer.Microsoft.com帐户,然后使用该帐户创建了一个新的Azure帐户,可以在其中添加Active Directory和该用户的Office许可证。其余代码已经在那里,并且可以正常工作。