Graph PowerShell: Retrieve Emails from the Deleted Items Folder

Administrators often need to retrieve or audit emails from the "Deleted Items" folder in user mailboxes. Whether it’s assisting users in recovering deleted emails or performing compliance checks, automating this process can save valuable time and effort. This article provides a Graph PowerShell script to fetch and display all emails from the "Deleted Items" folder of a user's mailbox.

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"

# Retrieve the folder ID for the "Deleted Items" folder
$DeletedItemsFolder = Get-MgUserMailFolder -UserId $UserUPN -Filter "displayName eq 'Deleted Items'" -Select Id

if (-not $DeletedItemsFolder) {
    Write-Output "Deleted Items folder not found for $UserUPN."
    Disconnect-MgGraph
    return
}

$DeletedItemsFolderId = $DeletedItemsFolder.Id

# Fetch all emails from the Deleted Items folder
$DeletedEmails = Get-MgUserMailFolderMessage -UserId $UserUPN -MailFolderId $DeletedItemsFolderId -Select "id,subject,from,receivedDateTime"

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

# Disconnect from Microsoft Graph
Disconnect-MgGraph
                            

How the Script Works?

  1. Connect to Microsoft Graph: The script authenticates to Microsoft Graph using the Connect-MgGraph cmdlet with the Mail.Read permission.
  2. Retrieve the Deleted Items Folder:: The Get-MgUserMailFolder cmdlet retrieves the folder ID for the "Deleted Items" folder.
  3. Fetch Emails:The Get-MgUserMailFolderMessage cmdlet retrieves all emails in the "Deleted Items" folder, including their subject, sender, and received date.
  4. Display Results:Outputs the retrieved emails to the console for review.
  5. Export to CSV: Exports the list of deleted emails to a CSV file (DeletedItemsEmails.csv) for further analysis or reporting.
  6. Disconnect from Microsoft Graph:Ends the session with Microsoft Graph to free up resources.

Further Enhancements

  • Filter Emails by Date: Modify the script to retrieve only emails deleted within a specific date range:
  • -Filter "receivedDateTime ge 2024-01-01T00:00:00Z"
  • Include Additional Properties:: Fetch more details about the emails, such as attachment status or size:
  • -Select "id,subject,from,receivedDateTime,hasAttachments,size"
  • Automate for Multiple Users:Extend the script to process multiple mailboxes by iterating through a CSV file of user UPNs:
  • Import-Csv "UserList.csv" | ForEach-Object {
        $UserUPN = $_.UserPrincipalName
        # Insert script logic here
    }
  • Scheduled Cleanup:Automate periodic execution of the script using Task Scheduler or Azure Automation to monitor and report deleted emails regularly.
  • Log Results: Save the output to a text file for auditing purposes:
  • $DeletedEmails | Out-File -FilePath "DeletedItemsLog.txt"
  • Send Email Notifications: Email the exported report to administrators or security teams:
  • Send-MailMessage -To "admin@example.com" -Subject "Deleted Items Report" -Body "The report is attached." -Attachments $ExportPath

Possible Errors & Solutions

Error Cause Solution
Access Denied The account or app lacks Mail.Read permission Assign the necessary permissions in Azure AD and ensure admin consent is granted.
Folder Not Found The script cannot locate the Deleted Items folder Verify the folder name ("Deleted Items") and its existence in the user's mailbox.
No Emails Found The folder is empty. Ensure emails exist in the Deleted Items folder before running the script.
API Throttling Too many requests sent to Microsoft Graph in a short period. Add a delay between API requests for large mailboxes or multiple users.

Conclusion

This Graph PowerShell script simplifies the process of retrieving and exporting emails from the "Deleted Items" folder. By using this script, administrators can monitor mailbox activity, recover deleted messages, or audit user actions efficiently. With options for customization and automation, the script can be tailored to suit various organizational needs.

Suggested Reading

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

x