Monitor Emails in the Last 30 Days Using Graph PowerShell

In this article, we'll delve into a PowerShell script designed to retrieve emails from the past 30 days for all users within an organization. This script leverages Microsoft Graph PowerShell to streamline the process of fetching and exporting email data.


Script Overview

The provided script is a powerful tool for administrators to monitor recent email activity across their organization. Below is the complete script:

# Get all users
$users = Get-MgUser -All

# Create an empty array to store the data
$Data = @()

# Determine the date 30 days prior to today
$startDate = (Get-Date).AddDays(-30).ToString("yyyy-MM-dd")

# Loop through each user
foreach ($user in $users) {
    # Ensure the user has an associated email address
    if ($user.Mail) {
        $messages = Get-MgUserMessage -UserId $user.Id -All -Filter "ReceivedDateTime ge $startDate" -ErrorAction SilentlyContinue
        foreach ($message in $messages) {
            $Data += [PSCustomObject]@{
                ReceivedDateTime  = $message.ReceivedDateTime
                Subject           = $message.Subject
                Sender            = $message.Sender.EmailAddress.Address -join ''
                Recipient         = $message.ToRecipients.EmailAddress.Address -join ''
                InternetMessageId = $message.InternetMessageId
            }
        }
    }
}

# Display and export the data
$Data | Out-GridView
$Data | Export-Csv -Path "C:\temp\All_emails.csv" -NoTypeInformation -Encoding utf8

Script Output


Script Explanation

Fetching All Users:

$users = Get-MgUser -All

This command retrieves all users in the Microsoft 365 environment.

Creating a Data Array:

$Data = @()

An empty array is initialized to store the retrieved email data.

Determining the Start Date:

$startDate = (Get-Date).AddDays(-30).ToString("yyyy-MM-dd")

The script calculates the date 30 days before today.

Looping Through Each User:

foreach ($user in $users) {
    if ($user.Mail) {
        $messages = Get-MgUserMessage -UserId $user.Id -All -Filter "ReceivedDateTime ge $startDate" -ErrorAction SilentlyContinue
        foreach ($message in $messages) {
            $Data += [PSCustomObject]@{
                ReceivedDateTime  = $message.ReceivedDateTime
                Subject           = $message.Subject
                Sender            = $message.Sender.EmailAddress.Address -join ''
                Recipient         = $message.ToRecipients.EmailAddress.Address -join ''
                InternetMessageId = $message.InternetMessageId
            }
        }
    }
}

For each user, if they have an associated email address, the script fetches their emails received in the last 30 days. The fetched email details are stored in a custom PowerShell object and added to the $Data array.

Displaying and Exporting Data:

$Data | Out-GridView
$Data | Export-Csv -Path "C:\temp\All_emails.csv" -NoTypeInformation -Encoding utf8

The data is displayed in a grid view for quick inspection. The data is exported to a CSV file for further analysis or record-keeping.


Further Enhancements

Filtering by Specific Domains:

$messages = Get-MgUserMessage -UserId $user.Id -All -Filter "ReceivedDateTime ge $startDate and endswith(Sender/EmailAddress/Address, '@example.com')" -ErrorAction SilentlyContinue

You can modify the script to only fetch emails from specific domains by adding additional filters.

Including Additional Email Properties:

$Data += [PSCustomObject]@{
    ReceivedDateTime  = $message.ReceivedDateTime
    Subject           = $message.Subject
    Sender            = $message.Sender.EmailAddress.Address -join ''
    Recipient         = $message.ToRecipients.EmailAddress.Address -join ''
    InternetMessageId = $message.InternetMessageId
    BodyPreview       = $message.BodyPreview
    Importance        = $message.Importance
}

You may want to include more properties such as BodyPreview or Importance in the exported data.


Use Cases

  • Security Audits: Ensuring no suspicious emails are received by users within the organization.
  • Compliance Monitoring: Checking that users adhere to email usage policies.
  • Performance Analysis: Analyzing the volume and nature of email communication within the organization.

Possible Errors & Solutions

Permission Issues:

Connect-MgGraph -Scopes "Mail.Read"

Ensure the executing account has the necessary permissions to access user emails. Necessary Graph API permissions are User.Read.All and Mail.Read.

Rate Limiting:

try {
    $messages = Get-MgUserMessage -UserId $user.Id -All -Filter "ReceivedDateTime ge $startDate" -ErrorAction SilentlyContinue
} catch {
    Write-Host "Rate limit exceeded. Retrying in 60 seconds..."
    Start-Sleep -Seconds 60
    $messages = Get-MgUserMessage -UserId $user.Id -All -Filter "ReceivedDateTime ge $startDate" -ErrorAction SilentlyContinue
}

Microsoft Graph API has rate limits; consider implementing error handling and retries.


Conclusion

This PowerShell script serves as an effective tool for administrators to monitor email activities within their organization for the past 30 days. By leveraging Microsoft Graph PowerShell, it simplifies the process of fetching, analyzing, and exporting email data. Customizing and enhancing this script can provide deeper insights and more specific data tailored to organizational needs.

For more advanced use cases and further optimizations, regularly refer to the latest Microsoft Graph API documentation and best practices.


Related Articles:

Using Get-MgDirectoryRole in Graph PowerShell
Using Get-MgUserLicenseDetail in Graph PowerShell
Using Find-GraphMgCommand in Graph PowerShell
Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

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