无法使用 Microsoft Graph API 代表用户发送电子邮件(找不到租户 GUID 错误)

问题描述 投票:0回答:1

我们正在创建一个应用程序,我们可以为用户提供电子邮件服务,并且用户也可以安排电子邮件发送。我们正在使用 Java 上的 microsoft graph api 进行概念验证。为此,我们在 Microsoft Azure 上创建了一个应用程序,在应用程序上设置权限并添加用户。我正在使用 msalj 和 microsoft graph api 为此编写 JAVA POC。这就是我正在做的事情。

IAuthenticationProvider iAuthProvider = new TokenCredentialAuthProvider(clientSecretCredential());
        
GraphServiceClient<Request> graphClient = GraphServiceClient
                .<Request>builder()
                .authenticationProvider(iAuthProvider)
                .buildClient();

//Creating msg body for Email
Message message = new Message();
graphClient.users(senderUserEmail).sendMail(UserSendMailParameterSet
        .newBuilder()
        .withMessage(message)
        .withSaveToSentItems(saveToSentItems)
        .build()).buildRequest()
    .post();

我使用 clientCredentialAuth 来获取令牌,我确实拥有所有值 ClientID、ClientSecret、TenantId。方法 clientSecretCredential() 定义如下。

    private ClientSecretCredential clientSecretCredential() {

        return new ClientSecretCredentialBuilder()
          .clientId(clientId)
          .tenantId(tenantId)
          .clientSecret(clientSecret)
          .build();
        }

但是当我运行代码时出现错误

{
  "error": {
    "code": "OrganizationFromTenantGuidNotFound",
    "message": "The tenant for tenant guid {tenantId} does not exist.",
    "innerError": {
      "errorUrl": "https://aka.ms/autherrors#error-InvalidTenant",
      "date": "2024-02-04T11:18:24"
    }
  }
}

不确定我在这里做错了什么。我探索了很多解决方案,但没有明白这里出了什么问题。

更新:@Rukmini 所建议的就是我们正在做的事情,但是是在 Java 方面。看来它不起作用,因为我们没有office365的许可证。我正在努力再次尝试。

azure azure-active-directory microsoft-graph-api outlook-restapi
1个回答
0
投票

要代表用户发送邮件,请检查以下内容:

创建 Microsoft Entra ID 应用程序并授予 API 权限:

enter image description here

我通过邮递员通过客户端凭证流程生成了访问令牌:

https://login.microsoftonline.com/TenantID/oauth2/v2.0/token

client_id:ClientID
client_secret:ClientSecret
grant_type:client_credentials
scope:https://graph.microsoft.com/.default

enter image description here

使用上述访问令牌,我能够成功发送邮件:

POST https://graph.microsoft.com/v1.0/me/sendMail
Content-type: application/json

{
  "message": {
    "subject": "Meet for lunch?",
    "body": {
      "contentType": "Text",
      "content": "The new cafeteria is open."
    },
    "toRecipients": [
      {
        "emailAddress": {
          "address": "[email protected]"
        }
      }
    ],
    "ccRecipients": [
      {
        "emailAddress": {
          "address": "[email protected]"
        }
      }
    ]
  },
  "saveToSentItems": "false"
}

enter image description here

如果用户未分配 Office 365 许可证,通常会出现错误 “OrganizationFromTenantGuidNotFound”。确保向租户订阅 Office 365 许可证。

enter image description here

如果问题仍然存在,请检查以下内容:

  • 验证您通过的
    TenantID
    是否有效。
  • 如果您使用个人 Outlook 帐户发送邮件,那么您必须使用交互式流程来发送邮件。请参阅 Sridevi 的这个SO Thread
  • 确保将 scope 传递为
    https://graph.microsoft.com/.default
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.