无法通过 AccessToken 和 ClientCredentialProvider 创建 GraphServiceClient 使用 Graph API(C# 控制台)发送电子邮件

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

我收到以下错误 代码: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"
                     }
                 }
             }
            };

以下功能所需的范围 string[] scopes = new string[] { "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)
            {

                
            }

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

我也检查了我在 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.

2.

3.

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