Search Emails for Specific Strings in the Email Body: Graph PowerShell

Searching for specific text in emails is a common administrative task. Whether you're investigating email delivery issues, locating specific reports, or assisting users in managing their mailboxes, a targeted search is invaluable. This article provides a PowerShell script using Microsoft Graph to search for a specific string in the body of emails within a user's Inbox.

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"

# Specify the search string to look for in the email body
$SearchString = "Your weekly PIM digest for MSFT"

# Search emails in the inbox containing the specified string
$Inbox = Get-MgUserMailFolder -UserId $UserUPN -Filter "displayName eq 'Inbox'" -Select Id

if (-not $Inbox) {
    Write-Output "Inbox not found for $UserUPN."
    Disconnect-MgGraph
    return
}

$InboxId = $Inbox.Id

# Use the $search parameter to search the email content
$MatchingEmails = Get-MgUserMailFolderMessage -UserId $UserUPN -MailFolderId $InboxId -Search $SearchString -Select "id,subject,from,receivedDateTime"

# Check if any matching emails are found
if ($MatchingEmails) {
    Write-Output "Found the following emails containing '$SearchString':"
    $EmailDetails = @()

    foreach ($email in $MatchingEmails) {
        Write-Output "Subject: $($email.Subject)"
        Write-Output "From: $($email.From.EmailAddress.Address)"
        Write-Output "Received: $($email.ReceivedDateTime)"
        Write-Output "------------------------------------"

        $EmailDetails += [PSCustomObject]@{
            Subject      = $email.Subject
            Sender       = $email.From.EmailAddress.Address
            ReceivedDate = $email.ReceivedDateTime
        }
    }

    # Export the details to a CSV file
    $ExportPath = "MatchingEmails.csv"
    $EmailDetails | Export-Csv -Path $ExportPath -NoTypeInformation
    Write-Output "Emails containing '$SearchString' have been exported to: $ExportPath"
} else {
    Write-Output "No emails found containing '$SearchString' in the inbox for $UserUPN."
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph
                            

How the Script Works

  1. Connect to Microsoft Graph: The script authenticates with Connect-MgGraph using the Mail.Read permission to access mailbox data.
  2. Retrieve Inbox Folder: The Get-MgUserMailFolder cmdlet fetches the folder ID for the Inbox.
  3. Search Emails for Specific Text: The $search parameter in Get-MgUserMailFolderMessage searches emails for the specified string across various fields, including the body and subject.
  4. Export Matching Emails: The results are saved to a CSV file (MatchingEmails.csv), making it easy to analyze and share.
  5. Disconnect from Graph: The script disconnects from Microsoft Graph after completing the task to free up resources.

Further Enhancements

  • Restrict Search to the Body Only: Refine the script to explicitly check the body content programmatically:
    $AllEmails = Get-MgUserMailFolderMessage -UserId $UserUPN -MailFolderId $InboxId -Select "id,subject,bodyPreview"
    $MatchingEmails = $AllEmails | Where-Object { $_.BodyPreview -like "*$SearchString*" }
  • Filter by Date Range: Add a date filter to focus on recent emails:
    -Filter "receivedDateTime ge 2024-01-01T00:00:00Z"
  • Expand Search Scope: Search across multiple folders, such as "Archive" or "Sent Items," by iterating through folder IDs.
  • Process Multiple Users: Extend the script to loop through a list of users from a CSV file:
    Import-Csv "UserList.csv" | ForEach-Object {
        $UserUPN = $_.UserPrincipalName
        # Insert script logic here
    }
  • Automate Reporting: Schedule the script to run periodically using Task Scheduler or Azure Automation and email the results to administrators:
    Send-MailMessage -To "admin@example.com" -Subject "Search Results for $SearchString" -Body "The report is attached." -Attachments $ExportPath

Possible Errors & Solutions

Error Cause Solution
Access Denied The account or app lacks Mail.Read permission Grant the required permissions in Azure AD and ensure admin consent.
Inbox Not Found The script cannot locate the Inbox folder Verify the folder name ("Inbox") and its existence in the user's mailbox.
No Emails Found No emails match the search string Ensure the search string is correct and matches the email content.
API Throttling Too many requests sent in a short time Add a delay between API requests for large mailboxes or multiple users.

Conclusion

This Graph PowerShell script provides a straightforward way to search for specific strings in the body of emails, helping administrators locate critical communications and support user requests. With options for exporting results and automating tasks, this script is a valuable tool for managing email workflows efficiently. Try it in your environment and tailor it to your specific needs.

Suggested Reading

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