【问题标题】:Unable to send Email using Graph API (C# Console) by creating GraphServiceClient through AccessToken as well as ClientCredentialProvider无法通过 AccessToken 以及 ClientCredentialProvider 创建 GraphServiceClient 来使用 Graph API(C# 控制台)发送电子邮件
【发布时间】:2020-10-09 03:52:00
【问题描述】:

我收到以下错误 代码: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)
            {

                
            }

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

我还检查了我在 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 azure-active-directory microsoft-graph-api microsoft-graph-sdks microsoft-graph-mail


    【解决方案1】:

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

    如果您订阅了 o365,您会在此处看到。

    1.

    2.

    3.

    【讨论】:

    • 我可以使用 Graph API 购买和分配 Office365 许可证吗?
    • @Marcus hi Marcus,你不能使用图表购买 Off365 许可证,但你可以分配它。见这里。 docs.microsoft.com/en-us/graph/api/…
    • 谢谢 - 不幸的是,它有点带走了我的整个集成点,因为我想自动化一个入职流程。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-01-23
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 2021-12-05
      • 2015-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多