Playwright QA Automation QA Tools

Harnessing Microsoft Graph API with Playwright and TypeScript for Efficient Email Reading 

Harnessing Microsoft Graph API with Playwright and TypeScript for Efficient Email Reading

Automation is critical for efficiency and accuracy in today’s dynamic web environment. Integrating powerful tools like Microsoft Graph API with automation frameworks such as Playwright and TypeScript can significantly enhance the capabilities of your web applications. This article explores leveraging the Microsoft Graph API for Efficient Email Reading as part of a Playwright automation workflow. 

Introduction to Microsoft Graph API

Microsoft Graph API is a comprehensive and versatile tool that provides developers with programmatic access to a wide array of data and services available within the Microsoft 365 ecosystem. This includes Outlook, OneDrive, Azure Active Directory, Microsoft Teams, and more services. By leveraging the Graph API, developers can build applications that integrate seamlessly with these services to enhance productivity and efficiency. 

The Microsoft Graph API enables developers to perform a variety of actions and retrieve valuable insights from the data stored in Microsoft 365. This can range from basic operations, such as reading and sending emails, managing calendars, and accessing user profiles, to more complex tasks like interacting with organizational charts, handling files in OneDrive, and even monitoring and managing security insights. 

In this article, we will focus on using the Microsoft Graph API to read emails from an Outlook inbox. This involves authenticating with Microsoft 365, making requests to the Graph API, and processing the responses to extract useful information from the emails. By following this approach, developers can automate email-related tasks, integrate email data into other applications, and create more efficient workflows within their organization. 

Setting Up the Environment

Before we dive into the code, let’s set up the environment. Make sure you have Node.js installed on your machine. Then, follow these steps: 

Step 1: Initialize a new Node.js project

Create a directory email-automation

Initialize a new Node.js project

Navigate to email-automation directory  

Efficient Email Reading with Microsoft Graph API

Create a new package.json using command “npm init – y” file in your project directory with default values. This command is particularly useful for setting up a new Node.js project quickly without manually answering all the configuration prompts. 

Efficient Email Reading with Microsoft Graph API

Step 2: Install the necessary packages

Installing the required dependencies using npm install playwright @microsoft/microsoft-graph-client isomorphic-fetch will set up your project with the necessary packages for web automation, Microsoft Graph API interaction, and fetching resources in a Node.js environment. Here’s a breakdown of each package and its purpose: 

  • Playwright: A Node.js library to automate web browsers. Useful for end-to-end testing and UI automation. 
  • @microsoft/microsoft-graph-client: A Microsoft Graph client library for accessing various Microsoft services like Outlook, OneDrive, etc.
  • isomorphic-fetch: A Fetch API implementation for both Node.js and browser environments, useful for making HTTP requests 
Install the necessary packages

Step 3: Create the directory structure

Create directory using the command “mkdir -p src/{pages,tests,utils}” 

Create the directory structure

Create locator file using command “touch src/selectors.ts” 

Efficient Email Reading with Microsoft Graph API

Configuring Microsoft Graph API

To use the Microsoft Graph API, you need to register an application in the Azure portal and obtain the client ID, tenant ID, and client secret. 

1. Register your application in the Azure portal

  • In the Azure portal, select Microsoft Entra ID
  • Select App Registrations.  
Efficient Email Reading with Microsoft Graph API
  • Select New registration
  • For Supported account types, select Accounts in this organization directory only. Leave the other options as it is.  
Efficient Email Reading with Microsoft Graph API

2. Select Register 

  • Application ID (client ID)
  • After registering a new application, you can find the application (client) ID and Directory (tenant) ID from the overview menu. Make a note of the values for use later. 
Efficient Email Reading with Microsoft Graph API

3. Configure API permissions to allow access to Mail. Read scope. 

  1. Navigate to “API permissions” in the left-hand menu of your registered application. 
  2. Click on the “Add permission” button. 
  3. Select “Microsoft Graph”
  4. Choose “Application permissions”
  5. Search for and select “Mail.Read”. This allows the application to read mail in all mailboxes without a signed-in user. 
  6. Click “Add permissions”
  7. Grant Admin Consent 
    • After adding the permission, you will see the Mail. Read permission listed but not yet granted for the organization. 
    • Click on the “Grant admin consent for [your organization]” button. 
    • A confirmation dialog will appear; click “Yes” to grant consent. 

5. Generate a client secret and note down the client ID, tenant ID, and client secret

  1. Navigate to “Certificates & secrets” in the left-hand menu. 
  2. Click on “New client secret”
  3. Add a description (e.g., “EmailAutomationSecret”) and select an expiration period (e.g., 1 year, 2 years, or custom). 
  4. Click “Add”
  5. Copy the generated secret value immediately as it will be hidden once you leave the page. This value will be used as your client_secret. 

Creating Utility Functions

Let’s create a utility function to handle authentication and email fetching using Microsoft Graph API. 

src/utils/auth.ts: 

import { Client } from "@microsoft/microsoft-graph-client"; 

import "isomorphic-fetch";



export async function getAuthenticatedClient(clientId: string, clientSecret: string, tenantId: string): Promise<Client> {

const tokenResponse = await fetch(`https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`, {

method: 'POST',

headers: {

'Content-Type': 'application/x-www-form-urlencoded'

},

body: new URLSearchParams({

client_id: clientId,

scope: 'https://graph.microsoft.com/.default',

client_secret: clientSecret,

grant_type: 'client_credentials'

})

});



const tokenData = await tokenResponse.json();

const client = Client.init({

authProvider: (done) => {

done(null, tokenData.access_token);

}

});



return client;

}

src/utils/email.ts: 

import { Client } from "@microsoft/microsoft-graph-client"; 



export async function fetchEmails(client: Client) {

const messages = await client.api('/me/messages')

.select('subject,bodyPreview,from')

.top(10)

.get();



return messages.value;

}

Writing Playwright Tests 

Now, let’s write Playwright tests that will use these utility functions. 

src/tests/email.test.ts

import { test, expect } from '@playwright/test'; 

import { getAuthenticatedClient } from '../utils/auth';

import { fetchEmails } from '../utils/email';



const clientId = 'YOUR_CLIENT_ID';

const clientSecret = 'YOUR_CLIENT_SECRET';

const tenantId = 'YOUR_TENANT_ID';



test('read emails using Microsoft Graph API', async ({ page }) => {

const client = await getAuthenticatedClient(clientId, clientSecret, tenantId);

const emails = await fetchEmails(client);



console.log('Emails:', emails);



expect(emails.length).toBeGreaterThan(0);

expect(emails[0]).toHaveProperty('subject');

});

Replace YOUR_CLIENT_ID, YOUR_CLIENT_SECRET, and YOUR_TENANT_ID with the values obtained from the Azure portal. 

Running the Tests 

To run the tests, use the following command: 

$ npx playwright test 

If everything is set up correctly, you should see the emails printed in the console and the tests passing. 

Conclusion 

Combining the power of Microsoft Graph API with Playwright and TypeScript for Efficient Email Reading can automate complex email interaction workflows. This setup enhances your application’s capabilities, saves time, and reduces errors. Explore further to integrate more Graph API functionalities into your automation scripts. 

bhushan-bagad

QA Lead

    Write A Comment