Graph PowerShell: Retrieve and Export Emails from the Junk Folder

Managing spam and phishing emails is a critical task for Microsoft 365 administrators. By analyzing emails flagged as spam or moved to the Junk Email folder, administrators can monitor email security, troubleshoot false positives, and ensure a clean mailbox environment. This article provides a Graph PowerShell script to retrieve and export emails from the Junk Email folder, along with detailed guidance and enhancements for practical use.

The Script

Below is the complete script to retrieve and export emails from the Junk Email folder:


# 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 the Junk Email folder ID
$JunkFolder = Get-MgUserMailFolder -UserId $UserUPN -Filter "displayName eq 'Junk Email'" -Select Id

if (-not $JunkFolder) {
    Write-Output "Junk Email folder not found in $UserUPN's mailbox."
    Disconnect-MgGraph
    return
}

$JunkFolderId = $JunkFolder.Id

# Fetch all emails from the Junk Email folder
$JunkEmails = Get-MgUserMailFolderMessage -UserId $UserUPN -MailFolderId $JunkFolderId -Select "id,subject,from,receivedDateTime"

# Check if any emails are found
if ($JunkEmails) {
    Write-Output "Found the following emails in the Junk Email folder:"
    foreach ($email in $JunkEmails) {
        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 = "JunkEmails.csv"
    $JunkEmails | Select-Object @{Name="Sender";Expression={$_.From.EmailAddress.Address}}, Subject, ReceivedDateTime | Export-Csv -Path $ExportPath -NoTypeInformation
    Write-Output "Emails from the Junk folder have been exported to: $ExportPath"
} else {
    Write-Output "No emails found in the Junk Email folder for $UserUPN."
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph
                            

How the Script Works

  1. Connect to Microsoft Graph
    The script uses the Connect-MgGraph cmdlet with the Mail.Read permission to access the specified mailbox.
  2. Retrieve Junk Folder ID
    The Get-MgUserMailFolder cmdlet fetches the ID of the Junk Email folder using its display name. This ID is necessary to query the folder’s contents.
  3. Retrieve Junk Emails:
    The Get-MgUserMailFolderMessage cmdlet retrieves all emails from the Junk Email folder.
  4. Display Results:
    Details of each email, such as subject, sender, and received date, are displayed in the PowerShell console.
  5. Export to CSV:
    Emails are exported to a CSV file named JunkEmails.csv, making it easy to analyze or share the report.
  6. Disconnect:
    Ends the session with Microsoft Graph using Disconnect-MgGraph.

Further Enhancements

  • Filter Emails by Date: Limit the retrieval to recent emails using a date filter:
  • -Filter "receivedDateTime ge 2024-01-01T00:00:00Z"
  • Include Additional Properties: Retrieve and export more email properties, such as importance or isRead:
    -Select "id,subject,from,receivedDateTime,importance,isRead"
  • Process Multiple Users: Automate the retrieval of Junk folder emails for multiple users using a CSV file:
    Import-Csv "UserList.csv" | ForEach-Object {
        $UserUPN = $_.UserPrincipalName
        # Insert the script logic here
    }                                 
    }
  • Notify Administrators: o Automatically send the exported report to administrators or security teams:
    Send-MailMessage -To "security@example.com" -Subject "Junk Email Report" -Body "The report is attached." -Attachments $ExportPath
  • Log Emails for Auditing: Save a detailed log of all retrieved emails to a text file:
    $JunkEmails | Select-Object Subject, ReceivedDateTime | Out-File -FilePath "JunkEmailLog.txt"

Possible Errors and Solutions

Error Cause Solution
Access Denied Insufficient permissions to access the mailbox. Ensure the Mail.Read permission is granted in Azure AD for the account..
Junk Email Folder Not Found The Junk Email folder has been renamed or doesn’t exist. Verify the folder name in the mailbox and adjust the script accordingly.
No Emails Found The Junk Email folder is empty. Check the mailbox settings to ensure emails are routed to the Junk Email folder.
Throttling Limits Exceeded Too many requests sent in a short time. Add a delay between processing multiple mailboxes to avoid throttling.

Conclusion

This Graph PowerShell script provides an efficient way to retrieve and export emails from the Junk Email folder in a user’s mailbox. By automating the process and exporting the results, administrators can monitor spam activity, investigate false positives, and ensure email security. With options for filtering and bulk processing, this script is a valuable tool for managing email content across an organization.

Suggested Reading

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