Setting up Microsoft Graph API in Node

Do you ever find yourself needing to send Outlook emails in the background as well as requiring read/write access to an Outlook calendar account? Setting up with Microsoft Graph API gives you access to all of Outlook’s functions. That means you can set up the connection as a background application without prompting for user login. Here’s how:

1. Microsoft Azure Settings

  • First, add an App within App Registrations.
  •  Under Manage -> API Permissions -> Add a permission.
  •  To use the Graph API with a token instead of prompting user sign ins, choose Application Permissions rather than Delegated Permissions.
  • From the list, select all the features you want to access.
  •  Once you’ve added all the permissions, be sure to click Grant admin consent for (your app).

2. Auth Credentials

  • Get the right credentials from Microsoft Azure.
  • Client ID can be found under Overview.
  • Client Secret
    • Under Manage -> Certificates & Secret -> Client Secrets -> New client secret.
    • Client Secret is the Value from the newly generated secret.
  •  Tenant ID – can be found under Overview.

3. Getting a Token

After getting all the right credentials from Microsoft Azure account, we can set up the auth configuration along with an API call with the token needed.


const msal = require("@azure/msal-node");
const msalConfig = {
  auth: {
    clientId: config.get("microsoft.clientId"),
    clientSecret: config.get("microsoft.clientSecret"),
    authority: `https://login.microsoftonline.com/${config.get(
      "microsoft.tenantId"
    )}`,
  },
};
const tokenRequest = {
  scopes: ["https://graph.microsoft.com/.default"],
};

const cca = new msal.ConfidentialClientApplication(msalConfig);

const authResponse = await cca.acquireTokenByClientCredential(tokenRequest);

console.log("Got an auth token! ", authResponse.accessToken);

//Given the token,you can now set it to the header of any Axios calls made to Microsoft Graph API
const authHeader = (token: string) => {
  return {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  };
};

Using the Graph API

Once we have the auth header set up and the correct token fetched, we can use any of the Graph API calls via Axios. Here’s a quick example of how to draft and send an email via Microsoft’s Graph API. A useful tool is Postman utilizing Microsoft’s Graph API’s Postman Collection.


//In order to send an email, we needed to draft the email first and get an emailId
const emailBody = {
  subject: "Sample Email (Test)",
  importance: "Low",
  body: {
    contentType: "HTML",
    content: `Hello!`,
  },
  toRecipients: [
    {
      emailAddress: {
        address: `${recipeintEmail}`,
      },
    },
  ],
};
const draftEmailURL = `https://graph.microsoft.com/v1.0/users/${userId}/messages`;
const response = await Axios.post(
  draftEmailURL,
  emailBody,
  authHeader(authResponse.accessToken)
);

const emailId = response.data.id;
const sendEmailURL = `https://graph.microsoft.com/v1.0/users/${userId}/messages/${emailId}/send`;
const response = await Axios.post(sendEmailURL, {}, authHeader(authResponse.accessToken));

Inside the Microsoft Graph API’s Postman collection, you’ll find many calls related to Events, Mail, People, etc.


In getting the authentication setup for Microsoft Azure in Node, we can take advantage of the Graph API in the background of any app.

Conversation
  • Erick says:

    What is the tokenRequest variable’s value? I’m not sure that was explained.

    • Jing Fan Jing Fan says:

      At the time of the post, the value for tokenRequest was:

      const tokenRequest = {
        scopes: ["https://graph.microsoft.com/.default"],
      };

      I would suggest double checking the most updated url.

      Edit: Good question and I will add this to the original code in the post!

  • Comments are closed.