Graph PowerShell: Search Emails by Subject Keyword

Managing emails effectively is a critical task for Microsoft 365 administrators. Sometimes, you need to search for specific emails based on keywords in their subject lines, whether for compliance, audits, or user support. This article introduces a Graph PowerShell script that allows you to search for emails containing specific keywords in their subject and export the results for analysis.

The Script

Here’s the complete script to search for emails by a keyword in their subject line and export the results to a CSV file:


# 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 keyword to search for in the email subject
$Keyword = "Important"

# Fetch emails that contain the specified keyword in their subject
$EmailsWithKeyword = Get-MgUserMessage -UserId $UserUPN -Filter "contains(subject, '$Keyword')" -Select "id,subject,from,receivedDateTime"

# Check if any emails are found
if ($EmailsWithKeyword) {
    Write-Output "Found the following emails with subject containing '$Keyword':"
    foreach ($email in $EmailsWithKeyword) {
        Write-Output "Subject: $($email.Subject)"
        Write-Output "From: $($email.From.EmailAddress.Address)"
        Write-Output "Received: $($email.ReceivedDateTime)"
        Write-Output "------------------------------------"
    }

    # Export the results to a CSV file
    $ExportPath = "EmailsWithKeyword.csv"
    $EmailsWithKeyword | Select-Object @{Name="Sender";Expression={$_.From.EmailAddress.Address}}, Subject, ReceivedDateTime | Export-Csv -Path $ExportPath -NoTypeInformation
    Write-Output "Emails with subject containing '$Keyword' have been exported to: $ExportPath"
} else {
    Write-Output "No emails found with subject containing '$Keyword' for $UserUPN."
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph
                            

How the Script Works

  1. Connect to Microsoft Graph:
    The script uses Connect-MgGraph to authenticate and access the mailbox with the Mail.Read permission.
  2. Search Emails by Keyword:
    The Get-MgUserMessage cmdlet retrieves emails where the subject contains the specified keyword using the contains filter.
  3. Display Results:
    Matching emails are listed in the PowerShell console, displaying their subject, sender, and received date.
  4. Export Results to CSV:
    The results are exported to a CSV file (EmailsWithKeyword.csv) for easy sharing or analysis.
  5. Disconnect from Graph:
    The script ends the session with Microsoft Graph after completing the task.

Further Enhancements

  1. Search by Multiple Keywords:
    Extend the script to iterate through multiple keywords and find all matching emails:
  2. $Keywords = @("Important", "Urgent", "Project")
    foreach ($Keyword in $Keywords) {
        $EmailsWithKeyword = Get-MgUserMessage -UserId $UserUPN -Filter "contains(subject, '$Keyword')" -Select "id,subject,from,receivedDateTime"
        # Process each keyword's results
    }
                                    
  3. Filter by Date Range:
    Schedule the script to run periodically using Task Scheduler or Azure Automation, ensuring unlicensed users are always assigned available licenses.
  4. -Filter "contains(subject, '$Keyword') and receivedDateTime ge 2024-01-01T00:00:00Z and receivedDateTime le 2024-12-31T23:59:59Z"
  5. Search Multiple Mailboxes:
    Automate the script to search for emails across multiple user mailboxes:
  6. Import-Csv "UserList.csv" | ForEach-Object {
        $UserUPN = $_.UserPrincipalName
        # Insert script logic here
    }
                                    
  7. Automate Reporting:
    Schedule the script to run periodically and email the report to administrators:
  8. Send-MailMessage -To "admin@example.com" -Subject "Email Keyword Report" -Body "Please find the attached report." -Attachments $ExportPath
  9. Log Search Results::
    Save a detailed log of all retrieved emails to a text file for auditing:
  10. $EmailsWithKeyword | Select-Object Subject, ReceivedDateTime | Out-File -FilePath "KeywordSearchLog.txt"

Possible Errors and Solutions

Error Cause Solution
Access Denied The account or application lacks the Mail.Read permission Grant the required permission in Azure AD and ensure admin consent is provided if necessary.
No Emails Found No emails match the specified keyword. Verify the keyword and ensure that the mailbox contains emails with matching subjects.
Invalid Filter Clause Syntax error in the OData filter query. Confirm the syntax of the contains filter and ensure that it matches the required format.
API Throttling Too many requests sent to Microsoft Graph in a short time. Add a delay between requests when processing multiple mailboxes or large datasets.

Conclusion

This Graph PowerShell script is a powerful tool for administrators to search for emails based on keywords in their subject. Whether for compliance, audits, or assisting users in locating important messages, this script offers a streamlined solution. By customizing the filters and automating the reporting process, administrators can save time and improve email management workflows.

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