Graph PowerShell: Search and Export Emails with PDF Attachments

Monitoring and managing email attachments is a key responsibility for Microsoft 365 administrators. Sensitive or important file types, like PDFs, often need to be tracked for compliance, audits, or security purposes. This article introduces a Graph PowerShell script to search for emails containing PDF attachments in a user's mailbox and export the details to a CSV file for reporting.

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 = "samadmin@7xh7fj.onmicrosoft.com"

# Specify the file type to search for in attachments (e.g., '.zip', '.pdf')
$AttachmentType = ".pdf"

# Fetch all emails with attachments
$EmailsWithAttachments = Get-MgUserMessage -UserId $UserUPN -Filter "hasAttachments eq true" -Select "id,subject,receivedDateTime,from"

# Check if emails with attachments are retrieved
if ($EmailsWithAttachments) {
    $EmailsWithSpecificAttachments = @()

    foreach ($email in $EmailsWithAttachments) {
        # Retrieve attachments for each email
        $Attachments = Get-MgUserMessageAttachment -UserId $UserUPN -MessageId $email.Id

        foreach ($attachment in $Attachments) {
            # Ensure the attachment matches the specified file type
            if ($attachment.Name -and $attachment.Name -like "*$AttachmentType") {
                $EmailsWithSpecificAttachments += [PSCustomObject]@{
                    Subject        = $email.Subject
                    Sender         = $email.From.EmailAddress.Address
                    ReceivedDate   = $email.ReceivedDateTime
                    AttachmentName = $attachment.Name
                    AttachmentSize = $attachment.Size
                }
            }
        }
    }

    # Export the details to a CSV file
    if ($EmailsWithSpecificAttachments.Count -gt 0) {
        $ExportPath = "EmailsWithSpecificAttachments.csv"
        $EmailsWithSpecificAttachments | Export-Csv -Path $ExportPath -NoTypeInformation
        Write-Output "Emails with '$AttachmentType' attachments have been exported to: $ExportPath"
    } else {
        Write-Output "No emails found with '$AttachmentType' attachments for $UserUPN."
    }
} else {
    Write-Output "No emails with attachments were found for $UserUPN."
}

Disconnect-MgGraph
                            

How the Script Works

  • Connect to Microsoft Graph: The script uses the Connect-MgGraph cmdlet to authenticate with Mail.Read permissions, enabling read-only access to email data.
  • Fetch Emails with Attachments: It retrieves all emails where hasAttachments eq true using the Get-MgUserMessage cmdlet.
  • Filter Attachments: For each email, the script fetches its attachments using the Get-MgUserMessageAttachment cmdlet and checks if the attachment name ends with .pdf.
  • Log Matching Emails: Emails with matching attachments are added to an array for export.
  • Export Results to CSV: The script exports the details of matching emails, including subject, sender, received date, attachment name, and size, to a CSV file.
  • Disconnect: Ends the session with Microsoft Graph using the Disconnect-MgGraph cmdlet.

Further Enhancements

  • Include Additional Filters: Add filters to refine results, such as unread emails or high-importance messages:
    -Filter "hasAttachments eq true and isRead eq false and importance eq 'high'"
  • Handle Multiple Mailboxes: Process a list of users from a CSV file:
    Import-Csv "UserList.csv" | ForEach-Object {
        $UserUPN = $_.UserPrincipalName
        # Run the script logic for each user
    }
  • Include Subfolders: Extend the script to search emails in specific folders or across subfolders.
  • Automate Reporting: Schedule the script to run periodically and email the results to administrators:
    Send-MailMessage -To "admin@example.com" -Subject "PDF Attachment Report" -Body "The report is attached." -Attachments $ExportPath

Possible Errors & Solutions

Error Cause Solution
Access Denied The account lacks the required Mail.Read permissions. Grant the Mail.Read permission to the application or user account in Azure AD.
No Emails Found No emails meet the criteria or the mailbox is empty. Verify the mailbox contents and adjust the file type or filters.
Throttling Limits Reached Too many requests sent to Microsoft Graph in a short period. Implement a delay between requests or reduce the scope of the query.
Property Missing The attachment properties retrieved do not include the Name. Verify attachment types using the @odata.type property.

Conclusion

This Graph PowerShell script provides an efficient way to search for and track specific attachment types, like PDFs, across user mailboxes. Whether for auditing, compliance, or mailbox management, it offers flexibility and scalability for administrators. By exporting results to a CSV file, the script ensures that data can be analyzed and reported as needed.

Try out this script in your environment and feel free to customize it further for your organization’s requirements. Let us know how it helps streamline your email management tasks!

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