在React应用程序中通过Microsoft Graph API发送电子邮件时出现OrganizationFromTenantGuidNotFound和401 Unauthorized错误

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

我正在开发一个 React 应用程序,并尝试使用 Microsoft Graph API 和 OAuth2 身份验证发送电子邮件。但是,当我尝试发送电子邮件时,收到 401 未经授权错误。这是我遵循的流程:

用户使用 MSAL(Microsoft 身份验证库)登录并授予“Mail.Send”和“User.Read”权限。 我通过 msalInstance.acquireTokenPopup() 获取访问令牌。 我使用 axios.post() 通过 Microsoft Graph API 发送电子邮件,并在授权标头中包含访问令牌。

这是我遇到的错误:

POST https://graph.microsoft.com/v1.0/me/sendMail 401 (Unauthorized)
Error message:
Error during login or sending email: 
AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', ...}
Response error:
{error: {code: "OrganizationFromTenantGuidNotFound", message: "The tenant for tenant guid 'd600ee99-eb85-4281-a0c5-18cc87425a9e' does not exist."}}
The response error indicates:

{ error: { code: "OrganizationFromTenantGuidNotFound", message: "The tenant for tenant guid 'd600ee99-eb85-4281-a0c5-18cc87425a9e' does not exist." } }

我正在使用 UPN 以 .onmicrosoft.com 结尾的本地用户发送电子邮件。 我尝试过: 仔细检查权限(“Mail.Send”、“User.Read”)。 确保使用正确的 Microsoft 租户和订阅。 确保帐户已登录并正确获取令牌。我附上了 api 权限屏幕截图。在此处输入图像描述 我的代码:

 export const msalConfig = {
    auth: {
      clientId: "my-client-id", 
      authority: "https://login.microsoftonline.com/<tenand-id>", 
      redirectUri: "http://localhost:3000", // Adjust as per your app
    },
  };

import React from "react";
import { PublicClientApplication } from "@azure/msal-browser";
import { msalConfig } from "./msalConfig";
import axios from "axios";

const GraphApiTest = () => {
  const loginAndSendEmail = async () => {
    const msalInstance = new PublicClientApplication(msalConfig);
    await msalInstance.initialize();

    try {
      // Login and acquire access token
      const loginResponse = await msalInstance.loginPopup({
        scopes: ["Mail.Send", "User.Read"],
      });
      console.log("Login successful:", loginResponse);

      const account = msalInstance.getAllAccounts()[0];
      const tokenResponse = await msalInstance.acquireTokenPopup({
        account,
        scopes: ["Mail.Send", "User.Read"],
      });

      const accessToken = tokenResponse.accessToken;
      console.log("Access Token acquired:", accessToken);

      const emailPayload = {
        message: {
          subject: "Test Email from React App",
          body: {
            contentType: "Text",
            content: "This is a test email sent from my React app via Microsoft Graph API.",
          },
          toRecipients: [
            {
              emailAddress: {
                address: "[email protected]",
              },
            },
          ],
        },
        saveToSentItems: "true",
      };

      const response = await axios.post(
        "https://graph.microsoft.com/v1.0/me/sendMail",
        emailPayload,
        {
          headers: {
            Authorization: `Bearer ${accessToken}`,
            "Content-Type": "application/json",
          },
        }
      );

      console.log("Email sent successfully:", response.data);
    } catch (error) {
      console.error("Error during login or sending email:", error);

      if (error.response) {
        console.error("Response error:", error.response.data);
      }
    }
  };

  return (
    <div>
      <button onClick={loginAndSendEmail}>Send Email via Outlook</button>
    </div>
  );
};

export default GraphApiTest;

问题: 谁能解释为什么我收到此“OrganizationFromTenantGuidNotFound”和“401 Unauthorized”错误?该错误消息表明租户 ID 存在问题。我应该采取哪些步骤来解决此问题并通过 Microsoft Graph API 成功发送电子邮件?

reactjs azure-active-directory microsoft-graph-api azure-ad-msal http-status-code-401
1个回答
0
投票

发生错误是因为您的用户帐户没有分配发送邮件所需的有效 Microsoft 365 许可证。

要解决该错误,请确保将 active Microsoft 365 许可证分配给本地用户帐户,如下所示:

enter image description here

就我而言,我注册了一个应用程序并授予了与以下相同的权限:

enter image description here

当我通过使用具有 active Microsoft 365 许可证的用户登录来使用以下代码文件运行 React 应用程序时,我得到了如下响应:

src/components/GraphApiTest.js:

import React, { useState } from "react";
import { PublicClientApplication } from "@azure/msal-browser";
import { msalConfig } from "../msalConfig";
import axios from "axios";

const GraphApiTest = () => {
  const [statusMessage, setStatusMessage] = useState(""); // State to hold status messages

  const loginAndSendEmail = async () => {
    const msalInstance = new PublicClientApplication(msalConfig);
    await msalInstance.initialize();

    try {
      // Login and acquire access token
      const loginResponse = await msalInstance.loginPopup({
        scopes: ["Mail.Send", "User.Read"],
      });
      console.log("Login successful:", loginResponse);

      const account = msalInstance.getAllAccounts()[0];
      const tokenResponse = await msalInstance.acquireTokenPopup({
        account,
        scopes: ["Mail.Send", "User.Read"],
      });

      const accessToken = tokenResponse.accessToken;
      console.log("Access Token acquired:", accessToken);

      const emailPayload = {
        message: {
          subject: "Test Email from React App",
          body: {
            contentType: "Text",
            content: "This is a test email sent from my React app via Microsoft Graph API.",
          },
          toRecipients: [
            {
              emailAddress: {
                address: "[email protected]",
              },
            },
          ],
        },
        saveToSentItems: "true",
      };

      const response = await axios.post(
        "https://graph.microsoft.com/v1.0/me/sendMail",
        emailPayload,
        {
          headers: {
            Authorization: `Bearer ${accessToken}`,
            "Content-Type": "application/json",
          },
        }
      );

      console.log("Email sent successfully:", response.data);
      setStatusMessage("Email sent successfully!"); // Update success message
    } catch (error) {
      console.error("Error during login or sending email:", error);

      if (error.response) {
        console.error("Response error:", error.response.data);
        setStatusMessage("Failed to send email. Please try again."); // Update failure message
      } else {
        setStatusMessage("An unexpected error occurred.");
      }
    }
  };

  return (
    <div>
      <button onClick={loginAndSendEmail}>Send Email via Outlook</button>
      {/* Display status message */}
      {statusMessage && <p style={{ marginTop: "20px", color: "green" }}>{statusMessage}</p>}
    </div>
  );
};

export default GraphApiTest;

src/App.js:

import React from "react"; 
import GraphApiTest from "./components/GraphApiTest";

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>Send Email with Microsoft Graph API</h1>
        <p>
          Click the button below to log in and send an email via Microsoft Graph API.
        </p>
        <GraphApiTest />
      </header>
    </div>
  );
}

export default App;

src/msalConfig.js:

export const msalConfig = {
    auth: {
      clientId: "appId", 
      authority: "https://login.microsoftonline.com/tenantId", 
      redirectUri: "http://localhost:3000",
    },
    cache: {
      cacheLocation: "localStorage", 
      storeAuthStateInCookie: false, 
    },
  }; 

回复:

enter image description here

为了确认这一点,我在用户的

Sent Items
中检查了邮件成功发送的位置,如下所示:

enter image description here

参考:

如何修复错误:代码:OrganizationFromTenantGuidNotFound - Yakun Huang 的 Microsoft 问答 - MSFT

© www.soinside.com 2019 - 2024. All rights reserved.