How to calculate incoming and outgoing emails for mailboxes on Exchange on Prem.
This guide shows you how to create a PowerShell script for Exchange Server On-Prem that totals the number of incoming and outgoing mailboxes over the last 31 days.
Explanation:
- Date Range: The script is set to analyze the last 31 days, but you can adjust the
$StartDate
and$EndDate
variables as needed. - Get-Mailbox: Retrieves all mailboxes in the organisation.
- Get-MessageTrackingLog: Searches the message tracking logs for each mailbox for incoming (RECEIVE) and outgoing (SEND) emails.
- Measure-Object: Counts the number of emails found in each search.
- Results Collection: Stores the results in a collection and exports them to a CSV file.
Steps to Run the Script:
- Copy the below PoweShell command text from the below section and save the script to a
.ps1
file, e.g.,ExchangeStats.ps1
.
# Define the date range for the report
$StartDate = (Get-Date).AddDays(-31)
$EndDate = Get-Date
# Get all mailboxes
$mailboxes = Get-Mailbox -ResultSize Unlimited
# Initialize a collection to store results
$results = @()
foreach ($mailbox in $mailboxes) {
$emailAddress = $mailbox.PrimarySmtpAddress.ToString()
# Get incoming emails
$incomingEmails = Get-MessageTrackingLog -Start $StartDate -End $EndDate -Recipients $emailAddress -EventId RECEIVE | Measure-Object
$incomingCount = $incomingEmails.Count
# Get outgoing emails
$outgoingEmails = Get-MessageTrackingLog -Start $StartDate -End $EndDate -Sender $emailAddress -EventId SEND | Measure-Object
$outgoingCount = $outgoingEmails.Count
# Store the result
$results += [PSCustomObject]@{
User = $mailbox.DisplayName
EmailAddress = $emailAddress
IncomingEmails = $incomingCount
OutgoingEmails = $outgoingCount
}
}
# Export the results to a CSV file
$results | Export-Csv -Path "C:\ExchangeStats.csv" -NoTypeInformation
Write-Output "Report generated successfully and saved to C:\ExchangeStats.csv"
- Open Exchange Management Shell and navigate to where you have saved the
ExchangeStats.ps1
script.

- Run the script:
.\ExchangeStats.ps1
.
This will generate a CSV file (C:\ExchangeStats.csv
) with the number of incoming and outgoing emails for each mailbox.

- After the script has run successfully, it will display the below message.

- Here is an example of the output ExchangeStates.csv file.
