reactjsazure-active-directorymicrosoft-graph-apiazure-ad-msalhttp-status-code-401

Error OrganizationFromTenantGuidNotFound and 401 Unauthorized when Sending Email via Microsoft Graph API in React App


I'm working on a React app and attempting to send an email using Microsoft Graph API with OAuth2 authentication. However, when I try to send the email, I get a 401 Unauthorized error. Here's the flow I'm following:

User logs in using MSAL (Microsoft Authentication Library) and grants permissions for "Mail.Send" and "User.Read". I acquire the access token via msalInstance.acquireTokenPopup(). I send an email via the Microsoft Graph API using axios.post() with the access token in the authorization header.

Here’s the error I am encountering:

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

I am using local user where UPN ends with .onmicrosoft.com to send the email. I have tried: Double-checking the permissions ("Mail.Send", "User.Read"). Ensuring the correct Microsoft tenant and subscription are being used. Making sure the account is logged in and the token is acquired properly. i am attaching the api permissions screenshot.enter image description here My code:

 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: "gulzarjavaria2@gmail.com",
              },
            },
          ],
        },
        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;

heres the images for issue that email is not received: enter image description here enter image description here

Question: Can anyone explain why I'm getting this "OrganizationFromTenantGuidNotFound" and "401 Unauthorized" error? The error message suggests there's an issue with the tenant ID. What steps should I take to resolve this issue and successfully send the email via Microsoft Graph API?


Solution

  • The error occurred as your user account does not have valid Microsoft 365 license assigned, that is required to send mails.

    To resolve the error, make sure to assign active Microsoft 365 license to local user account like this:

    enter image description here

    In my case, I registered one application and granted same permissions as below:

    enter image description here

    When I ran react app with below code files by signing in with user having active Microsoft 365 license, I got response like this:

    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: "sridevi.machaxxxxxxxx@gmail.com",
                  },
                },
              ],
            },
            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, 
        },
      }; 
    

    Response:

    enter image description here

    To confirm that, I checked the same in user's Sent Items where mail sent successfully as below:

    enter image description here

    Reference:

    How can I fix Error: Code: OrganizationFromTenantGuidNotFound - Microsoft Q&A by Yakun Huang - MSFT