Using Graph PowerShell to Retrieve/Export Emails with Large Attachments

Managing mailbox storage efficiently is crucial for Microsoft 365 administrators. Large attachments in emails often consume significant space, and identifying them manually can be time-consuming. With Graph PowerShell, you can automate this process and pinpoint emails with oversized attachments, helping streamline storage management.

In this article, we’ll explore how to use a PowerShell script to retrieve and export emails with large attachments.


The Script

Here’s the complete script to retrieve and export emails with attachments exceeding a specified size threshold:

# 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 attachment size threshold (in bytes)
$AttachmentSizeThreshold = 10MB # Example: 10MB = 10 * 1024 * 1024 bytes
                                
# Convert threshold to bytes if specified in MB or KB
$AttachmentSizeThresholdBytes = $AttachmentSizeThreshold * 1024 * 1024
                                
# Query to fetch emails with large attachments
$EmailsWithLargeAttachments = Get-MgUserMessage -UserId $UserUPN -Select "id,subject,from,hasAttachments" -Filter "hasAttachments eq true"
                                
# Check if any emails with attachments are found
if ($EmailsWithLargeAttachments) {
        $LargeAttachmentEmails = @()
                                
        foreach ($email in $EmailsWithLargeAttachments) {
            $Attachments = Get-MgUserMessageAttachment -UserId $UserUPN -MessageId $email.Id
            foreach ($attachment in $Attachments) {
                if ($attachment.Size -ge $AttachmentSizeThresholdBytes) {
                    $LargeAttachmentEmails += [PSCustomObject]@{
                        Subject = $email.Subject
                        Sender  = $email.From.EmailAddress.Address
                        Size    = $attachment.Size
                        FileName = $attachment.Name
                        ReceivedDate = $email.ReceivedDateTime
                    }
                    }
                }
            }
                                
            # Export large attachment details to a CSV file
            if ($LargeAttachmentEmails) {
                    $ExportPath = "LargeAttachmentEmails.csv"
                    $LargeAttachmentEmails | Export-Csv -Path $ExportPath -NoTypeInformation
                    Write-Output "Emails with large attachments have been exported to: $ExportPath"
                } else {
                    Write-Output "No emails with attachments exceeding the size threshold were found."
                }
} else {
    Write-Output "No emails with attachments were found for $UserUPN."
}                     
# Disconnect from Microsoft Graph
Disconnect-MgGraph


How the Script Works

  1. Connect to Graph: : The script authenticates to Microsoft Graph with the Mail.Read scope, enabling it to access mailbox messages.
  2. Define Threshold: It specifies a size threshold (in bytes) to identify large attachments.
  3. Fetch Emails with Attachments: The script retrieves all emails containing attachments using the hasAttachments eq true filter.
  4. Analyze Attachment Size: For each email, it checks the size of all attachments and identifies those exceeding the specified threshold.
  5. Export Data: The details of emails with large attachments are saved to a CSV file, including subject, sender, attachment size, file name, and received date.
  6. Disconnect: The session ends after the operation, ensuring no lingering connections to Microsoft Graph.

Further Enhancements

  • Combine Multiple Criteria: Modify the -Filter to include additional conditions like importance eq 'high' or isRead eq false for more specific results..
  • -Filter "hasAttachments eq true and importance eq 'high'"
  • Analyze Multiple Mailboxes: Loop through a list of user mailboxes from a CSV file to generate comprehensive reports across multiple accounts:
  • Import-Csv "UserList.csv" | ForEach-Object {
    $UserUPN = $_.UserPrincipalName
    # Run the script logic for each user
    }
                                    
  • Automated NotificationsIntegrate an email notification system to alert administrators about users with large attachments:
  • Send-MailMessage -To "admin@example.com" -Subject "Large Attachment Report" -Body "The report is ready." -Attachments $ExportPath

Possible Errors and Solutions

Access Denied

  • Cause: Insufficient permissions in Microsoft Graph.
  • Solution: Grant the Mail.Read permission in Azure AD for the application or user account.

Invalid Filter Clause

  • Cause: The filter syntax is incorrect or uses unsupported properties
  • Solution: Ensure proper filter syntax (e.g., hasAttachments eq true) and verify property names.

No Attachments Found

  • Cause: No emails with attachments meet the criteria.
  • Solution: Confirm the threshold and test the script with a lower size limit.

Too Many Results

  • Cause: A large dataset can exceed Graph API limits.
  • Solution: Implement paging using the $Top parameter to retrieve results in batches.

Conclusion

This script offers an efficient way to identify and manage emails with large attachments, helping administrators optimize mailbox storage and maintain compliance. By exporting the data to a CSV file, it also allows for further analysis and reporting. With customizable filters and bulk processing options, the script is adaptable for various administrative tasks.

Try this script in your environment and let us know how it simplifies your email management workflows!


Related Articles:

Using Get-MgDirectoryRole in Graph PowerShell
Using Get-MgUserLicenseDetail in Graph PowerShell
Using Find-GraphMgCommand in Graph PowerShell
Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

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