Graph PowerShell: Archive Emails from a Specific Folder

Efficient email management is essential for maintaining productivity and ensuring compliance with organizational policies. Archiving old emails is a common task for administrators to reduce mailbox clutter, improve performance, and organize content. This article introduces a Graph PowerShell script to move older emails from a specific folder (e.g., Inbox) to an archive folder, streamlining mailbox management.

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.ReadWrite"

# Specify the User Principal Name (UPN) of the mailbox
$UserUPN = "user@yourtenant.onmicrosoft.com"

# Specify the source folder and target (archive) folder
$SourceFolderName = "Inbox"
$ArchiveFolderName = "Archive"

# Specify the date threshold for archiving (e.g., emails older than January 1, 2024)
$ArchiveDate = "2024-01-01T00:00:00Z"

# Get the source folder ID
$SourceFolder = Get-MgUserMailFolder -UserId $UserUPN -Filter "displayName eq '$SourceFolderName'" -Select Id
if (-not $SourceFolder) {
    Write-Output "Source folder '$SourceFolderName' not found in $UserUPN's mailbox."
    Disconnect-MgGraph
    return
}
$SourceFolderId = $SourceFolder.Id

# Get the archive folder ID (create it if it doesn't exist)
$ArchiveFolder = Get-MgUserMailFolder -UserId $UserUPN -Filter "displayName eq '$ArchiveFolderName'" -Select Id
if (-not $ArchiveFolder) {
    Write-Output "Archive folder '$ArchiveFolderName' not found. Creating it..."
    $ArchiveFolder = New-MgUserMailFolder -UserId $UserUPN -BodyParameter @{ displayName = $ArchiveFolderName }
}
$ArchiveFolderId = $ArchiveFolder.Id

# Fetch emails older than the specified date from the source folder
$EmailsToArchive = Get-MgUserMailFolderMessage -UserId $UserUPN -MailFolderId $SourceFolderId -Filter "receivedDateTime lt $ArchiveDate"

# Check if any emails meet the criteria
if ($EmailsToArchive) {
    Write-Output "Found the following emails to archive from '$SourceFolderName':"
    foreach ($email in $EmailsToArchive) {
        Write-Output "Subject: $($email.Subject)"
        Write-Output "Received: $($email.ReceivedDateTime)"
        Write-Output "------------------------------------"
    }

    # Move emails to the archive folder
    foreach ($email in $EmailsToArchive) {
        Move-MgUserMessage -UserId $UserUPN -MessageId $email.Id -DestinationId $ArchiveFolderId
        Write-Output "Archived email with Subject: $($email.Subject)."
    }
    Write-Output "All matching emails have been archived."
} else {
    Write-Output "No emails found to archive from '$SourceFolderName' for $UserUPN."
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph
                            

How the Script Works

  • Connect to Microsoft Graph: The script uses Connect-MgGraph with the Mail.ReadWrite permission to access and manage mailbox folders and messages.
  • Identify Source and Target Folders: The script retrieves the folder IDs of the source (Inbox) and target (Archive) folders. If the archive folder doesn’t exist, it is created using New-MgUserMailFolder.
  • Filter Emails by Date: The Get-MgUserMailFolderMessage cmdlet retrieves emails older than the specified date ($ArchiveDate) from the source folder using the receivedDateTime filter.
  • Move Emails: The script iterates through the filtered emails and uses Move-MgUserMessage to move them to the archive folder.
  • Disconnect: Finally, the script disconnects from Microsoft Graph to ensure there are no lingering connections.

Further Enhancements

  • Automate the Archiving Process: Schedule the script using Task Scheduler or Azure Automation to run periodically (e.g., weekly or monthly).
  • Apply Additional Filters: Archive emails based on multiple criteria, such as unread status or importance:
    -Filter "receivedDateTime lt $ArchiveDate and isRead eq false"
  • Process Multiple Mailboxes: Use a CSV file to archive emails for multiple users:
    Import-Csv "UserList.csv" | ForEach-Object {
        $UserUPN = $_.UserPrincipalName
        # Insert the script logic here
    }
  • Log Archived Emails: Export details of archived emails to a CSV file for auditing:
    $EmailsToArchive | Select-Object Subject, ReceivedDateTime | Export-Csv -Path "ArchivedEmailsLog.csv" -NoTypeInformation
  • Send Notifications: Email the summary of archived emails to administrators or users:
    Send-MailMessage -To "admin@example.com" -Subject "Archived Emails Report" -Body "The report is attached." -Attachments "ArchivedEmailsLog.csv"

Possible Errors and Solutions

Error Cause Solution
Access Denied The account lacks the required Mail.ReadWrite permission. Assign the Mail.ReadWrite permission to the user or app in Azure AD.
Source Folder Not Found The source folder does not exist in the mailbox. Verify the folder name and ensure it exists in the user’s mailbox.
No Emails Found No emails meet the specified criteria. Check the folder contents and ensure emails match the filter criteria (e.g., date).
Throttling Limits Exceeded Too many API requests in a short period. Implement a delay between requests or reduce the number of mailboxes processed in a single run.

Conclusion

This script provides a powerful way to archive emails from a specific folder to an archive folder within a user's mailbox. By automating the process, administrators can save time, reduce mailbox clutter, and ensure compliance with organizational policies. The flexibility to customize filters and extend the script to multiple users makes it an indispensable tool for managing Microsoft 365 mailboxes.

Try this script in your environment and customize it to meet your organization’s needs!


Suggested Reading

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