Get-MgUserMessage: How to Retrieve Microsoft 365 User Emails with Graph PowerShell
This guide explains how to use Get-MgUserMessage cmdlet in Microsoft Graph PowerShell to retrieve user emails. Learn to filter messages by properties like sender, subject and export results for analysis.
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)
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.
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.
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.
💡 Limit Message Payload with the -Property Parameter
By 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:
subject
from
receivedDateTime
hasAttachments
🔍 Use the -Filter Parameter to Narrow Down Results
You 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:
isRead
from/emailAddress/address
receivedDateTime
This helps streamline mailbox queries for better targeting and automation.
🏷️ Retrieve Emails with Specific Categories Assigned
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.
Suggested Reading:
How to Connect to Graph PowerShell
Using New-MgUserMessage in Graph PowerShell
Using Update-MgUserMessage in Graph PowerShell
Using Remove-MgUserMessage in Graph PowerShell
Using Send-MgUserMessage in Graph PowerShell