Monitoring email activity is an essential task for administrators, whether for security audits, compliance, or troubleshooting. With Graph PowerShell, you can automate the process of retrieving daily email activity for specific users, helping you track sent and received emails efficiently.
In this article, we will walk through a Graph PowerShell script that fetches and displays the number of emails sent and received by selected users on a given day.
Below is the Graph PowerShell script that retrieves the daily email activity (sent and received emails) for specific users:
# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Mail.Read"
# List of User Principal Names (UPNs)
$UserList = @("user1@yourtenant.onmicrosoft.com", "user2@yourtenant.onmicrosoft.com")
# Define the date
$Date = (Get-Date).ToString("yyyy-MM-dd")
foreach ($UserUPN in $UserList) {
Write-Output "Fetching email activity for $UserUPN on $Date..."
$EmailsReceived = Get-MgUserMessage -UserId $UserUPN -Filter "receivedDateTime ge $Date and receivedDateTime lt $($Date + 'T23:59:59Z')"
$EmailsSent = Get-MgUserMessage -UserId $UserUPN -Filter "sentDateTime ge $Date and sentDateTime lt $($Date + 'T23:59:59Z')"
Write-Output "User: $UserUPN"
Write-Output "Emails Received: $($EmailsReceived.Count)"
Write-Output "Emails Sent: $($EmailsSent.Count)"
Write-Output "---------------------------------------------"
}
# Disconnect from Microsoft Graph
Disconnect-MgGraph
$ActivitySummary = @()
foreach ($UserUPN in $UserList) {
$EmailsReceived = Get-MgUserMessage -UserId $UserUPN -Filter "receivedDateTime ge $Date and receivedDateTime lt $($Date + 'T23:59:59Z')"
$EmailsSent = Get-MgUserMessage -UserId $UserUPN -Filter "sentDateTime ge $Date and sentDateTime lt $($Date + 'T23:59:59Z')"
$ActivitySummary += [PSCustomObject]@{
User = $UserUPN
EmailsReceived = $EmailsReceived.Count
EmailsSent = $EmailsSent.Count
Date = $Date
}
}
$ExportPath = "DailyEmailActivity.csv"
$ActivitySummary | Export-Csv -Path $ExportPath -NoTypeInformation
Write-Output "Email activity report has been exported to: $ExportPath"
-Filter "receivedDateTime ge $Date and receivedDateTime lt $($Date + 'T23:59:59Z') and subject eq 'Important Report'"
Send-MailMessage -To "admin@example.com" -Subject "Daily Email Activity Report" -Body "The report is attached." -Attachments $ExportPath
This Graph PowerShell script simplifies the process of tracking email activity for specific users. Whether you need this data for compliance, security, or user support, this script provides a quick and efficient way to fetch daily email counts. By implementing further enhancements such as CSV export, automation, and notification emails, administrators can build a robust email monitoring solution.
Try it out in your environment and customize it based on your requirements.
Let us know if you found this useful by writing to us @ m365corner@gmail.com