Get Email Activity And Mailbox Usage Details Of All Users Using Graph API

In this article, I would like to explain the steps for fetching the email activity and details of all the O365 users using Graph API. In the previous one, we already saw how to Get all the site collections and their usage.

For my organization, we need all the users' email activities, such as sent mail count, received mail count, and read mail count in last 30 days. We have used Graph API to achieve this. Here, I’m sharing the steps involved to get the email activities and how to check the Graph API results in O365 portal reports.

Here is the sample output from the Graph API Email Activity in the beta version.

Get All The Users Email Activity And Mailbox Usage Using Graph API

From Microsoft documentation

“Microsoft Graph is the gateway to data and intelligence in Microsoft 365. Microsoft Graph provides a unified programmability model that you can use to take advantage of the tremendous amount of data in Office 365, Enterprise Mobility + Security, and Windows 10.

You can use the Microsoft Graph API to build apps for organizations and consumers that interact with the data of millions of users. With Microsoft Graph, you can connect to a wealth of resources, relationships, and intelligence, all through a single endpoint: https://graph.microsoft.com”

Reference URL - https://developer.microsoft.com/en-us/graph/docs/concepts/overview

Here is the Microsoft Documentation URL,

https://developer.microsoft.com/en-us/graph/docs/concepts/overview

Steps to retrieve Email activity details using node.js

Follow the below listed steps and code.

End Point URL -  https://graph.microsoft.com/v1.0/reports/getEmailActivityUserDetail(period='D30')

Graph Token URL - https://login.microsoftonline.com/{tenantID}/oauth2/v2.0/token

Graph Token body - client_id=" + configValues.clientId + "&scope=" + configValues.scope + "&client_secret=" + configValues.clientSecretId + "&grant_type=client_credentials

Step 1

Register the app in Azure AD using that client ID, Tenant ID, and secret key.

Follow the below URL to Register the app in Azure.

Make sure to check that your registered Azure app has permission to read the directory data.

Step 2

In your node.js solution, just create the config file and provide the below values. We have created the config file to avoid the hard-coded things. Provide your tenantId, clientId, and secret key. Please don't use the below mentioned one, it is just a sample (it won't work).
  1. {  
  2.     "scope""https%3A%2F%2Fgraph.microsoft.com%2F.default",  
  3.     "tenantId""7aa111ae-1ab6-4256-af4c-a0c1cdb4575d",  
  4.     "clientId""bff7fae8-c253-37e5-9b6a-e096bed54f11",  
  5.     "clientSecretId""XgfrmWfX0K/N7SRouCdAskTKrz0cnKN2rS12IkJ9SJk="  
  6. }  

Step 3

Refer to that config file in your JS file, as shown below.
  1. var request = require('sync-request');    
  2. var fs = require('fs');    
  3. var configValues = JSON.parse(fs.readFileSync('emailactivityconfig.json'));    

Step 4

Then, frame the Graph token URL and Graph token body to get the auth token.
  1. var graphAccessUrl = "https://login.microsoftonline.com/" + configValues.tenantId + "/oauth2/v2.0/token";    
  2. var graphTokenBody = "client_id=" + configValues.clientId + "&scope=" + configValues.scope + "&client_secret=" + configValues.clientSecretId + "&grant_type=client_credentials"  

Step 5

Get the Authorized token using the below method.
  1. varcontentType = "application/x-www-form-urlencoded; charset=utf-8";  
  2. vargraphTokenError = "Failed to get graph token";  
  3. vargraphToken = "";  
  4. //Call the get token method  
  5. getToken(graphAccessUrl, contentType, graphTokenBody, graphTokenError);  
  6. //This method is using to get the token from the graph token url and body  
  7. functiongetToken(url, type, content, errorMessage, callback) {  
  8.     var options = {  
  9.         'headers': {  
  10.             'Content-Type': type  
  11.         },  
  12.         'body': content  
  13.     };  
  14.     //Posting access parameters to the server  
  15.     vartokenResponse = httpPost(url, options);  
  16.     if (tokenResponse.statusCode === 200) {  
  17.         error = errorMessage;  
  18.         if (errorMessage === graphTokenError) {  
  19.             vartoken = JSON.parse(tokenResponse.body.toString('utf-8'));  
  20.             graphToken = token.access_token;  
  21.         }  
  22.         if (callback) {  
  23.             returncallback();  
  24.         }  
  25.     } else {  
  26.         log(errorMessage);  
  27.     }  
  28. }  

Step 6

Once you receive the token, make the HTTP call using endpoint and get the results.

Step 7

Email Activity Report in Graph API v1.0 provides the results as CSV format not in JSON format so we have no need to use the top. In a single API call, we can retrieve all the user results.

  1. var reqUrl = "https://graph.microsoft.com/v1.0/reports/getEmailActivityUserDetail (period='D30')";  
  2. var usersCount = 0;  
  3.   
  4. function getEmailActivityReportData(reqUrl) {  
  5.     try {  
  6.         console.log("Inside get user last logon data method!!!");  
  7.         var emailActivityRes = httpGet(encodeURI(reqUrl), GRAPH_TOKEN);  
  8.         if (emailActivityRes.statusCode == 200) {  
  9.             failIndex = 0;  
  10.             var parsedJson = convertCSVToJSON(emailActivityRes.body.toString('utf-8'));  
  11.             //add use case value to json valued array  
  12.             var parsJson = JSON.parse(parsedJson);  
  13.             if (parsJson) {  
  14.                 usersCount = usersCount + parsJson.length;  
  15.                 for (var i = 0; i < parsJson.length; i++) {  
  16.                     var currItem = parsJson[i];  
  17.                     if (currItem) {  
  18.                         //process your data here  
  19.                     }  
  20.                 }  
  21.             }  
  22.             console.log("Email users count : " + usersCount);  
  23.         } else {  
  24.             console.log("Email user activity api received failed response: " + emailActivityRes.statusCode)  
  25.         }  
  26.     }  
  27. catch (ex) {  
  28.     console.log(ex);  
  29. }  
  30. }  
  31. //The below method is using to convert the csv values to json values  
  32. function convertCSVToJSON(csv) {  
  33.     /// <summary>This function is used to convert CSV to JSON</summary>   
  34.     /// <param name="csv" type="String">CSV string</param>  
  35.     /// <returns type="Array">Return as JSON Array</returns>  
  36.     try {  
  37.         var lines = csv.split("\n");  
  38.         var result = [];  
  39.         var headers = lines[0].split(",");  
  40.         for (var i = 1; i < lines.length; i++) {  
  41.             var obj = {};  
  42.             if (lines[i]) {  
  43.                 var currentline = lines[i].split(",");  
  44.                 for (var j = 0; j < headers.length; j++) {  
  45.                     obj[headers[j]] = currentline[j];  
  46.                 }  
  47.                 result.push(obj);  
  48.             }  
  49.         }  
  50.         return JSON.stringify(result);  
  51.     } catch (ex) {  
  52.         console.log(ex + " in csvToJSON method...");  
  53.     }  

Step 8

Then, bind the results based on your requirement. You will receive the below object when you call the Email Activity API.

Get All The Users Email Activity And Mailbox Usage Using Graph API 

Steps to Check the Exchange Email activity details from the admin portal

Once you get the results, you can verify the results from O365 and also, follow the below-listed steps to verify the output.

Step 1

Log into Microsoft 365 Admin Center. Learn more here.

https://admin.microsoft.com/AdminPortal 

Step 2

Provide a valid username and password to log into your account.

Step 3

From Microsoft 365 Admin Center main menu, click the Reports option and then the Usage option.
 
Get All The Users Email Activity And Mailbox Usage Using Graph API 

Step 4

On the Usage pane, click "Select a report" drop-down list, expand Exchange and click the "Email activity" option.
 
Get All The Users Email Activity And Mailbox Usage Using Graph API 

Step 5

Click on the Export option; you will get the last 30 days report for email activities with relevant data.
 
Get All The Users Email Activity And Mailbox Usage Using Graph API 

Using the same endpoint, you can get the reports for 7 days, 30 days, 90 days, and 180 days.

https://graph.microsoft.com/v1.0/reports/getEmailActivityUserDetail (period='D30')

Reference Link

https://docs.microsoft.com/en-us/graph/api/reportroot-getemailactivityuserdetail?view=graph-rest-1.0

Summary

In this article, we have explored how to get the activity details of Exchange users, such as read, sent, received mail counts from the Office365 portal and using Graph API. I hope this article is useful to you. Please share your feedback in the comments section. Thanks for visiting my article.


Similar Articles