Graph PowerShell: Fetch Daily Emails Sent/Received

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.

The Script

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
                            

How the Script Works

  1. Connect to Microsoft Graph: The script begins by authenticating with Microsoft Graph using the Connect-MgGraph cmdlet. The Mail.Read permission is required to access user mailbox data.
  2. Define the List of Users and Date:
    • The script begins by authenticating with Microsoft Graph using the Connect-MgGraph cmdlet. The Mail.Read permission is required to access user mailbox data.
    • The date is dynamically set to today’s date, but it can be modified to fetch emails for a specific day.
  3. Retrieve Emails Received on the Specified Date:
    • The Get-MgUserMessage cmdlet is used to retrieve emails received by each user on the specified date.
    • A Filter parameter is applied to only fetch emails where receivedDateTime falls within the selected date.
  4. Retrieve Emails Sent on the Specified Date: Similarly, the script fetches emails sent by each user on the specified date using the sentDateTime filter.
  5. Display Results in the Console: The script prints the total number of emails sent and received by each user.
  6. Disconnect from Microsoft Graph: o Once the email data is retrieved, the script disconnects from Microsoft Graph to free up resources.

Further Enhancements

  • Export Results to CSV: Instead of just displaying the results, administrators can export the daily email activity to a CSV file for further analysis or record-keeping:
  • $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 Emails by Subject or Sender: If you want to track specific types of emails, you can modify the script to filter emails by subject keywords or sender:
  • -Filter "receivedDateTime ge $Date and receivedDateTime lt $($Date + 'T23:59:59Z') and subject eq 'Important Report'"
  • Automate Script Execution: Use Task Scheduler or Azure Automation to run the script daily and generate automated reports.
  • Notify Admins via Email Automatically email the results to administrators for daily monitoring:
  • Send-MailMessage -To "admin@example.com" -Subject "Daily Email Activity Report" -Body "The report is attached." -Attachments $ExportPath
  • Add Timezone Support The script currently fetches emails based on UTC time. If users are in different time zones, consider adjusting the filter accordingly.

Conclusion

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