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.
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
$users = Get-MgUser -All
This command retrieves all users in the Microsoft 365 environment.
$Data = @()
An empty array is initialized to store the retrieved email data.
$startDate = (Get-Date).AddDays(-30).ToString("yyyy-MM-dd")
The script calculates the date 30 days before today.
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.
$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.
$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.
$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.
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.
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.
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.
© m365corner.com. All Rights Reserved. Design by HTML Codex