Saturday, December 2, 2023
HomeMicrosoft 365Automating SharePoint File Analytics Reports via Email using Azure Functions and Microsoft...

Automating SharePoint File Analytics Reports via Email using Azure Functions and Microsoft Graph API

In today’s digital landscape, organizations are increasingly dependent on collaboration platforms like SharePoint Online to store and share documents. With the ever-growing volume of files and data, it’s crucial for businesses to keep track of their most important files and monitor their usage. SharePoint File Analytics provides a valuable solution, offering insights into the number of views, unique users, and other relevant metrics. However, manually checking these metrics can be time-consuming and cumbersome. Automating the process can save time and ensure that your team is always up-to-date on the usage of crucial files.

In this blog post, we’ll explore how you can automate SharePoint File Analytics Reports using Azure Functions and Microsoft Graph API. By combining these powerful tools, you can create a custom, scheduled email report that provides daily insights into the usage of specific files hosted on your SharePoint Online site. This solution not only streamlines the process of monitoring file activity but also allows you to tailor the report’s format to meet your organization’s unique needs and security constraints. Stay tuned as we dive into the step-by-step process of setting up this automated reporting system, and learn how to harness the power of Azure Functions and Microsoft Graph API to enhance your SharePoint experience.

To achieve this, you can use a combination of Microsoft Graph API to fetch the analytics data and an Azure Function with a Timer Trigger to send the email report daily. Follow these steps:

  1. Register an app in Azure Active Directory:
    • Go to Azure Portal (https://portal.azure.com).
    • Navigate to Azure Active Directory > App registrations > New registration.
    • Give your app a name, and under “Supported account types,” select the appropriate option.
    • Click “Register.”
  2. Grant the necessary permissions:
    • In the App registration, go to “API permissions” > “Add a permission.”
    • Select “Microsoft Graph” > “Application permissions.”
    • Add the following permissions:
      • Files.Read.All (to read files in SharePoint)
      • Sites.Read.All (to read site data)
      • User.Read.All (to read user profile data)
    • Click “Add permissions.”
    • Click “Grant admin consent for [Your Tenant].”
  3. Generate a client secret:
    • In the App registration, go to “Certificates & secrets.”
    • Click “New client secret.”
    • Give it a description, set the expiration, and click “Add.”
    • Copy the generated secret value (you’ll need it later).
  4. Create an Azure Function:
    • Go to the Azure Portal and create a new Function App.
    • Choose a Resource Group, give your Function App a name, and select the appropriate settings.
    • Click “Create.”
    • In the Function App, click “+” next to “Functions” and create a new Timer Trigger function with the desired schedule (e.g., every day at a specific time).
  5. Install the necessary packages:In the Azure Function, install the required packages, such as microsoft-graph-client, by adding them to the requirements.txt file.
  6. Write the code to fetch the analytics data and send the email:Here’s a sample Python script for your Azure Function to fetch analytics data and send an email:

import os
import requests
from msgraph.core import GraphClient, GraphClientError
from msgraph.core.middleware.authorization import AuthorizationMiddleware
from msgraph.core.middleware.middleware import Middleware
from msgraph.core.middleware.options import AuthProviderConfig
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def main(mytimer: func.TimerRequest) -> None:
    client_id = os.environ['APP_CLIENT_ID']
    client_secret = os.environ['APP_CLIENT_SECRET']
    tenant_id = os.environ['TENANT_ID']
    file_path = os.environ['FILE_PATH']
    site_id = os.environ['SITE_ID']

    token_endpoint = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token'
    token_data = {
        'grant_type': 'client_credentials',
        'client_id': client_id,
        'client_secret': client_secret,
        'scope': 'https://graph.microsoft.com/.default'
    }
    token_r = requests.post(token_endpoint, data=token_data)
    token = token_r.json().get('access_token')

    if not token:
        raise ValueError('Failed to acquire token.')

    graph_client = GraphClient(token)

    # Get file analytics
    analytics_url = f'https://graph.microsoft.com/v1.0/sites/{site_id}/drive/root:{file_path}:/analytics'
    analytics_data = graph_client.get(analytics_url).json()

    # Get user views
    views = analytics_data['allTime']['lastSevenDays']['uniqueUsers']

    # Prepare and send email report
    email_subject = "Daily SharePoint File Analytics Report

Most Popular