Graph PowerShell: Generate Email Activity Summary for User Mailbox

Monitoring mailbox activity is a crucial part of email management for administrators. By analyzing the number of total and unread emails across folders, you can assess user engagement, identify potential issues, and optimize mailbox organization. This article introduces a Graph PowerShell script to retrieve and export an email activity summary for a user’s mailbox.

The Script

Here’s the script to generate a summary of email activity, including total emails and unread emails in each folder, and export the results to a CSV file:


# Install the Microsoft Graph PowerShell module if not already installed
# Install-Module -Name Microsoft.Graph -Scope CurrentUser

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Mail.Read"

# Specify the User Principal Name (UPN) of the mailbox to query
$UserUPN = "user@yourtenant.onmicrosoft.com"

# Retrieve all mail folders
$MailFolders = Get-MgUserMailFolder -UserId $UserUPN -Select "id,displayName,unreadItemCount,totalItemCount"

# Check if any folders are retrieved
if ($MailFolders) {
    Write-Output "Retrieved email activity for $($UserUPN):"
    $ActivitySummary = @()

    foreach ($folder in $MailFolders) {
        $ActivitySummary += [PSCustomObject]@{
            FolderName     = $folder.DisplayName
            TotalEmails    = $folder.TotalItemCount
            UnreadEmails   = $folder.UnreadItemCount
        }
        Write-Output "Folder: $($folder.DisplayName), Total Emails: $($folder.TotalItemCount), Unread Emails: $($folder.UnreadItemCount)"
    }

    # Export the activity summary to a CSV file
    $ExportPath = "EmailActivitySummary.csv"
    $ActivitySummary | Export-Csv -Path $ExportPath -NoTypeInformation
    Write-Output "Email activity summary exported to: $ExportPath"
} else {
    Write-Output "No mail folders found for $($UserUPN)."
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph
                            

How the Script Works

  • Connect to Microsoft Graph: The script uses the Connect-MgGraph cmdlet with the Mail.Read permission to access folder-level data in the user’s mailbox.
  • Retrieve Folder Information: The Get-MgUserMailFolder cmdlet retrieves all mail folders in the user’s mailbox and extracts the id, displayName, totalItemCount, and unreadItemCount properties.
  • Generate Summary: The script loops through each folder, creating a summary object with the folder name, total emails, and unread emails.
  • Export Data: The results are exported to a CSV file (EmailActivitySummary.csv) for easy analysis and reporting.
  • Disconnect: The script terminates the session with Microsoft Graph using Disconnect-MgGraph.

Further Enhancements

  1. Filter by Specific Folders:
    Restrict the activity summary to specific folders like Inbox or Archive
  2. $MailFolders = Get-MgUserMailFolder -UserId $UserUPN -Filter "displayName eq 'Inbox'" -Select "id,displayName,unreadItemCount,totalItemCount"
  3. Add Date Filters:
    Include a filter to analyze folder activity for a specific date range (e.g., emails received in the past month).
  4. Process Multiple Mailboxes:
    Automate the script for multiple users by looping through a list of mailboxes:
  5. Import-Csv "UserList.csv" | ForEach-Object {
        $UserUPN = $_.UserPrincipalName
        # Insert script logic here
    }
  6. Scheduled Automation:
    Schedule the script to run periodically using Task Scheduler or Azure Automation and generate automated reports.
  7. Enhanced Reporting:
    Add columns to the report, such as folder sizes or the last email received date.
  8. Send Summary via Email:
    Email the exported CSV report to administrators:
  9. Send-MailMessage -To "admin@example.com" -Subject "Mailbox Activity Report" -Body "The report is attached." -Attachments $ExportPath

Frequently Asked Questions

  • Can I run the mailbox activity summary for multiple users at once?
  • Yes. You can loop through a list of user IDs or UPNs from a CSV file and run the mailbox activity summary for each user. This is especially useful for reporting on activity across departments or the entire organization.

  • What permissions are required to fetch mailbox activity details?
  • You need the Mail.Read or Mail.ReadBasic delegated permissions (for your own mailbox) or Mail.Read / Mail.ReadWrite application permissions (for other users) to retrieve mailbox activity data using Graph PowerShell.

  • How can I export mailbox activity summaries for analysis?
  • You can pipe the results into Export-Csv to save them as a CSV file, which makes it easy to analyze unread counts, message volumes, and folder usage in Excel or Power BI.

  • Will the summary include archived or shared mailboxes?
  • No, by default the script retrieves mailbox activity for user mailboxes only. For shared or archived mailboxes, you need to explicitly specify their UPNs or mailbox IDs.


Possible Errors & Solutions

Error Cause Solution
Access Denied Insufficient permissions to access mailbox data. Ensure the user or app has the Mail.Read permission in Azure AD.
No Mail Folders Found The mailbox is empty, or the user has no folders Verify that the mailbox exists and contains folders.
Export Path Not Found The specified export path for the CSV file is invalid or inaccessible. Ensure the directory exists and is writable.
API Throttling Too many requests sent to Microsoft Graph in a short time. Add delays between requests when processing multiple mailboxes.

📊 Highlight Spot-Check Folders with High Unread Counts

After generating the summary, look for folders where the UnreadEmails count is disproportionately high — this could indicate neglected folders like Junk Email or old newsletter repositories, and may warrant cleanup or user coaching.
📅 Add a “Last Message Received Date” for Trend Analysis

Enhance your export by including each folder’s LastMessageReceivedDateTime. This adds a layer of insight into user activity patterns — helpful when identifying stale folders or reporting on mailbox usage trends over time.

Conclusion

This Graph PowerShell script provides administrators with a quick and efficient way to analyze email activity in a user's mailbox. By generating a summary of total and unread emails across folders, the script helps monitor mailbox usage, identify potential issues, and optimize email organization. With options for customization, automation, and reporting, this script is a valuable tool for day-to-day email management.

© m365corner.com. All Rights Reserved. Design by HTML Codex