Get-MgUserMessage cmdlet allows you to retrieve Outlook email messages from a user's mailbox. This article will cover the cmdlet syntax, provide usage examples, offer tips, discuss use cases, highlight possible errors and solutions, and conclude with the benefits of using this cmdlet.
Cmdlet Syntax
Get-MgUserMessage -UserId <String> [-MessageId <String>]
- -UserId: Specifies the ID or UPN of the user. (Required)
- -MessageId: Specifies the ID of the message to retrieve. (Optional)
🚀 Community Edition Released!
Try the M365Corner Microsoft 365 Reporting Tool — your DIY pack with 20+ out-of-the-box M365 reports for Users, Groups, and Teams.
Usage Examples
Retrieve All Messages for a User
Get-MgUserMessage -UserId "john.doe@contoso.com"
This command retrieves all messages for the specified user.
Retrieve a Specific Message by Message ID
Get-MgUserMessage -UserId "john.doe@contoso.com" -MessageId "AAMkAGI2T..."
This command retrieves a specific message by its message ID.
Retrieve Messages with Specific Properties
$User = "samadmin@7xh7fj.onmicrosoft.com"
Get-MgUserMessage -All -UserId "$User" |
Select-Object Subject, InternetMessageId, ReceivedDateTime,
@{Name = "Sender"; Expression = { $_.Sender.EmailAddress.Address }},
@{Name = "Recipients"; Expression = { $_.ToRecipients.EmailAddress.Address -join ' ' }} |
Out-GridView
This command retrieves messages with specific properties and displays them in a grid view.
Filter Messages by Subject
Get-MgUserMessage -UserId "john.doe@contoso.com" -Filter "contains(subject,'Project Update')"
This command retrieves messages that contain "Project Update" in the subject.
Filter Messages by Date
Get-MgUserMessage `
-UserId "samadmin@7xh7fj.onmicrosoft.com" `
-Filter "receivedDateTime ge 2024-12-01T00:00:00Z" `
-Property Id,Subject,From,ReceivedDateTime `
-Top 50
This command retrieves messages greater than 2024-12-01 and displays the results in the console.
Filter for Emails Within a Specific Date Range
This command retrieves messages within the 2024-11-01 and 2024-11-30 date range and display the results in the console.
# Get emails sent within a specific date range
Get-MgUserMessage `
-UserId "samadmin@7xh7fj.onmicrosoft.com" `
-Filter "sentDateTime ge 2024-11-01T00:00:00Z and sentDateTime le 2024-11-30T23:59:59Z" `
-Property Id,Subject,ToRecipients,SentDateTime
Search Messages
Get-MgUserMessage -UserId "john.doe@contoso.com" -Search "Project Update"
This command searches messages that contain "Project Update".
Retrieve a Limited Number of Messages
Get-MgUserMessage -UserId "john.doe@contoso.com" -Top 10
This command retrieves the top 10 messages for the specified user.
Retrieve Emails Received from a Specific Sender
Get-MgUserMessage -UserId "user@domain.com" -Filter "from/emailAddress/address eq 'ceo@domain.com'" -Top 10
This command fetches the top 10 messages received from ceo@domain.com, using a direct filter on the sender's email address.
Retrieve Emails with Attachments
Place this under the Usage Examples section, preferably after Retrieve Emails Received from a Specific Sender.
Connect-MgGraph -Scopes "Mail.Read"
$UserId = "user@domain.com"
Get-MgUserMessage `
-UserId $UserId `
-Filter "hasAttachments eq true" `
-Property Id,Subject,From,ReceivedDateTime,HasAttachments `
-Top 50 |
Select-Object `
Subject,
ReceivedDateTime,
HasAttachments,
@{Name = "Sender"; Expression = { $_.From.EmailAddress.Address }},
Id
What this script does
This script retrieves emails that contain attachments from a user’s mailbox. It selects useful properties such as subject, sender, received date, attachment status, and message ID.
Why this example is useful
This is helpful for administrators who need to identify emails with attachments during mailbox reviews, security checks, migration planning, or compliance investigations.
Cmdlet Tips
- Use Filters for Efficiency: Use the -Filter parameter to narrow down the results and improve performance.
- Expanding Properties: Use the -ExpandProperty parameter to retrieve related entities in one call, reducing the need for multiple requests.
- Paging Through Results: Use -Top and -Skip parameters to page through large sets of messages.
- Use Out-GridView PowerShell cmdlet: Using Out-GridView cmdlet often in combination with Get-MgUserMessage helps you view more properties than what gets displayed on the console.
Use Cases
- Monitoring Employee Mailboxes for Security or Compliance:
- Scenario: Organizations need to ensure compliance with data protection regulations and monitor email communications for potential security risks or inappropriate content.
- Implementation: Use Get-MgUserMessage to retrieve specific messages or message metadata from employee mailboxes. This can be useful for auditing emails, ensuring compliance with internal policies, and identifying any violations.
- Benefit: Helps maintain compliance with regulatory frameworks (e.g., GDPR, HIPAA) and ensures that email communications align with the organization’s security and data protection policies.
- Identifying and Exporting Important Emails:
- Scenario: Certain business-critical emails, such as contract negotiations or project updates, need to be easily accessible or exported for record-keeping or legal purposes.
- Implementation: Use Get-MgUserMessage to filter messages by specific properties (e.g., subject, sender, date range) and export them for archiving, reporting, or further processing. This is particularly useful in legal discovery processes or in maintaining communication records for compliance audits.
- Benefit: Simplifies the process of locating and exporting critical emails, ensuring that important communications are readily available for future reference or legal purposes.
- Automating Mailbox Management Tasks:
- Scenario: Organizations may need to regularly manage mailbox messages, such as archiving older emails, deleting spam, or categorizing specific messages.
- Implementation: Use Get-MgUserMessage in conjunction with other cmdlets (e.g., Remove-MgUserMessage, Move-MgUserMessage) to automate tasks like deleting messages from a specific sender or moving all messages older than 90 days to an archive folder.
- Benefit: Automates routine mailbox management tasks, reducing the manual workload for administrators and helping to maintain organized, efficient mailboxes.
- Tracking Communication During Critical Events:
- Scenario: During important projects, security incidents, or critical events (e.g., mergers, security breaches), organizations may want to track and analyze email communication to ensure transparency and coordination.
- Implementation: Use Get-MgUserMessage to filter messages based on key events, subject lines, or project-related keywords to gather all relevant email communications. These messages can be analyzed or exported to review how a situation was handled, improving post-event reporting.
- Benefit: Provides detailed insights into communication patterns during high-stakes events, helping teams analyze responses, identify gaps, and improve coordination for future events.
Possible Errors and Fixes
| Error | Solution |
| Insufficient privileges to complete the operation. | Ensure the executing user has the required permissions (e.g., Mail.Read) in the Microsoft Graph API. Assign appropriate roles or permissions. |
| Resource not found. | Verify the -UserId and -MessageId parameters. Ensure the user and message exist and are correctly specified. |
| Invalid filter clause | Check the syntax of the -Filter parameter. Ensure it follows the OData filter query format. |
Frequently Asked Questions
- What is Get-MgUserMessage used for?
Get-MgUserMessage is a Microsoft Graph PowerShell cmdlet used to retrieve emails from a user’s mailbox. It supports filtering by properties like subject, sender, importance, or date received. - How can I retrieve unread emails from a user’s mailbox?
Use the -Filter parameter to specify unread messages:Get-MgUserMessage -UserId "" -Filter "isRead eq false" -All - Can I export retrieved messages to a CSV file?
Yes, you can export email properties like subject, sender, and date received using the following script:$Messages = Get-MgUserMessage -UserId "" -All $Messages | Select-Object Subject, Sender, ReceivedDateTime | Export-Csv -Path "C:\Path\To\File.csv" -NoTypeInformation - Is it possible to retrieve emails from a specific folder, such as the 'Inbox' or 'Sent Items'?
Yes, to retrieve emails from a specific folder, you can use the Get-MgUserMailFolderMessage cmdlet along with the folder's ID. First, retrieve the folder ID using Get-MgUserMailFolder, then fetch the messages$folder = Get-MgUserMailFolder -UserId "user@domain.com" -Filter "displayName eq 'Inbox'" $folderId = $folder.Id # Retrieve messages from the specified folder Get-MgUserMailFolderMessage -UserId "user@domain.com" -MailFolderId $folderId -All - What permissions are required to use the Get-MgUserMessage cmdlet?
To execute the Get-MgUserMessage cmdlet, your account must have the appropriate Microsoft Graph API permissions. The required permissions include Mail.Read or Mail.ReadBasic. Ensure that these permissions are granted and consented to in Azure Active Directory. - Can I use Get-MgUserMessage to find emails with attachments?
Yes. Use the hasAttachments property with the -Filter parameter.
Get-MgUserMessage -UserId "user@domain.com" -Filter "hasAttachments eq true"
This retrieves messages where the email has one or more attachments.
No. Get-MgUserMessage only retrieves message details. To retrieve attachment details, use Get-MgUserMessageAttachment. To download the actual attachment content, use the relevant attachment content cmdlet depending on the attachment type.
This distinction is useful because message retrieval and attachment retrieval are handled separately in Microsoft Graph PowerShell.
-Property ParameterBy default,
Get-MgUserMessage returns basic message data.
To improve performance and keep output concise, use the -Property parameter to retrieve only the fields you need — such as:
subjectfromreceivedDateTimehasAttachments
-Filter Parameter to Narrow Down ResultsYou can apply filters to search for specific messages — such as unread items, emails from particular senders, or messages within a date range.
Useful filterable properties include:
isReadfrom/emailAddress/addressreceivedDateTime
You can filter messages based on assigned Outlook categories (like
"Important" or "Finance") using the -Filter parameter with categories/any().Get-MgUserMessage -UserId user@domain.com -Filter "categories/any(c:c eq 'Finance')"
This is helpful for retrieving categorized emails based on user-defined or automated labels.
Conclusion
The Get-MgUserMessage cmdlet is a powerful tool for administrators to manage and retrieve emails from user mailboxes in Microsoft 365. By leveraging this cmdlet, administrators can automate email-related tasks, generate detailed reports, and troubleshoot email issues efficiently. Proper use of filters, properties, and paging parameters can enhance the performance and relevance of the retrieved data.
By understanding the syntax, usage examples, tips, use cases, and potential errors, administrators can make the most out of the Get-MgUserMessage cmdlet to streamline email management in their organizations.
If You Prefer the Graph API Way
Note: To interact with user mail via Graph API, use the /users/{id}/messages or /me/messages endpoint. You can filter, sort, or limit fields using OData query options like $filter, $orderby, and $select.
- Retrieve All Messages for a User
- Retrieve a Specific Message by Message ID
- Retrieve Messages with Specific Properties
- Filter Messages by Subject
# Replace with the target user's UPN or ID
$userId = "john.doe@yourtenant.onmicrosoft.com"
$response = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/users/$userId/messages"
if ($response.value) {
foreach ($msg in $response.value) {
Write-Output "Subject : $($msg.subject)"
Write-Output "From : $($msg.from.emailAddress.address)"
Write-Output "ID : $($msg.id)"
Write-Output "`n"
}
} else {
Write-Output "No messages found."
}
# Replace with actual UPN and message ID
$userId = "john.doe@yourtenant.onmicrosoft.com"
$messageId = "AAMkADhkZT...f5AAA="
$uri = "https://graph.microsoft.com/v1.0/users/$userId/messages/$messageId"
$response = Invoke-MgGraphRequest -Method GET -Uri $uri
if ($response) {
Write-Output "Subject : $($response.subject)"
Write-Output "Sender : $($response.from.emailAddress.name)"
Write-Output "Body Preview: $($response.bodyPreview)"
} else {
Write-Output "Message not found or access denied."
}
# Retrieve only Subject, Sender, and Received Time
$userId = "john.doe@yourtenant.onmicrosoft.com"
$uri = "https://graph.microsoft.com/v1.0/users/$userId/messages?`$select=subject,from,receivedDateTime"
$response = Invoke-MgGraphRequest -Method GET -Uri $uri
if ($response.value) {
foreach ($msg in $response.value) {
Write-Output "Subject : $($msg.subject)"
Write-Output "From : $($msg.from.emailAddress.address)"
Write-Output "Received : $($msg.receivedDateTime)"
Write-Output "`n"
}
} else {
Write-Output "No messages returned or access denied."
}
# Find messages with subject containing the word 'Invoice'
$userId = "john.doe@yourtenant.onmicrosoft.com"
$filter = "`$filter=contains(subject,'Invoice')"
$uri = "https://graph.microsoft.com/v1.0/users/$userId/messages?$filter"
$response = Invoke-MgGraphRequest -Method GET -Uri $uri
if ($response.value) {
foreach ($msg in $response.value) {
Write-Output "Subject : $($msg.subject)"
Write-Output "ID : $($msg.id)"
Write-Output "`n"
}
} else {
Write-Output "No messages matched the subject filter."
}
💡 Other supported filters include isRead, importance, receivedDateTime, and more.
Required Permissions
You’ll need one of the following delegated or app permissions:
Mail.ReadMail.ReadWrite
Graph API Documentation
Suggested Reading:
How to Connect to Graph PowerShellUsing New-MgUserMessage in Graph PowerShell
Using Update-MgUserMessage in Graph PowerShell
Using Remove-MgUserMessage in Graph PowerShell
Using Send-MgUserMessage in Graph PowerShell