Graph PowerShell: Retrieve and Export Unread High-Importance Emails

Efficient email management is crucial for ensuring that critical messages are not overlooked. Unread emails marked with high importance often indicate tasks or communications that require immediate attention. This article introduces a Graph PowerShell script to identify unread high-importance emails in a user's mailbox and export the results for analysis or reporting.

The Script


# Install the Microsoft Graph PowerShell module if not already installed
# Install-Module -Name Microsoft.Graph -Scope CurrentUser

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Mail.Read"

# Specify the User Principal Name (UPN) of the mailbox to query
$UserUPN = "user@yourtenant.onmicrosoft.com"

# Fetch unread emails with high importance
$UnreadHighImportanceEmails = Get-MgUserMessage -UserId $UserUPN -Filter "isRead eq false and importance eq 'high'" -Select "id,subject,from,receivedDateTime"

# Check if any unread high-importance emails are found
if ($UnreadHighImportanceEmails) {
    Write-Output "Found the following unread high-importance emails:"
    foreach ($email in $UnreadHighImportanceEmails) {
        Write-Output "Subject: $($email.Subject)"
        Write-Output "From: $($email.From.EmailAddress.Address)"
        Write-Output "Received: $($email.ReceivedDateTime)"
        Write-Output "------------------------------------"
    }

    # Export the emails to a CSV file
    $ExportPath = "UnreadHighImportanceEmails.csv"
    $UnreadHighImportanceEmails | Select-Object @{Name="Sender";Expression={$_.From.EmailAddress.Address}}, Subject, ReceivedDateTime | Export-Csv -Path $ExportPath -NoTypeInformation
    Write-Output "Unread high-importance emails have been exported to: $ExportPath"
} else {
    Write-Output "No unread high-importance emails found for $UserUPN."
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph
                            

How the Script Works

  • Connect to Microsoft Graph: The script uses the Connect-MgGraph cmdlet with the Mail.Read permission to authenticate and access mailbox data.
  • Fetch Emails: The Get-MgUserMessage cmdlet retrieves unread emails (isRead eq false) with high importance (importance eq 'high'), using an OData filter.
  • Display Results: Matching emails are displayed in the PowerShell console, showing their subject, sender, and received date.
  • Export to CSV: The results are exported to a CSV file for reporting, containing the sender, subject, and received date.
  • Disconnect: The script ends the session with Microsoft Graph using the Disconnect-MgGraph cmdlet.

Further Enhancements

  • Refine Filters: Include additional criteria, such as filtering emails from a specific sender or emails received within a date range:
    -Filter "isRead eq false and importance eq 'high' and receivedDateTime ge 2024-01-01T00:00:00Z"
  • Process Multiple Mailboxes: Loop through a list of users stored in a CSV file to check multiple mailboxes:
    Import-Csv "UserList.csv" | ForEach-Object {
        $UserUPN = $_.UserPrincipalName
        # Run the script logic here
    }
  • Automate Reporting: Schedule the script using Task Scheduler or Azure Automation to run periodically and send reports to administrators:
    Send-MailMessage -To "admin@example.com" -Subject "Unread High-Importance Emails Report" -Body "The report is attached." -Attachments $ExportPath
  • Visual Reporting: Use tools like Power BI or Excel to visualize the exported data and gain insights into unread high-priority emails.

Possible Errors and Solutions

Error Cause Solution
Access Denied Insufficient permissions. Ensure the account or application has the Mail.Read permission in Azure AD.
No Emails Found No emails meet the specified criteria. Verify the mailbox contents and ensure there are unread high-importance emails.
Invalid Filter Clause Syntax error in the OData filter query. Confirm the filter string is correctly formatted, e.g., isRead eq false and importance eq 'high'.
Graph API Throttling Too many requests sent in a short period. Reduce the number of mailboxes processed or implement a delay between queries.

Conclusion

This Graph PowerShell script is an invaluable tool for administrators to monitor unread high-importance emails, ensuring critical messages are not missed. With flexibility to filter, export, and automate, it streamlines mailbox management tasks and provides actionable insights for both users and IT teams.

Try this script in your environment and let us know how it improves your email management workflows. If you have additional use cases or enhancements, feel free to share them!

© m365corner.com. All Rights Reserved. Design by HTML Codex