Automate Email Archiving with Graph PowerShell

Managing mailbox size in Microsoft 365 is critical for keeping your environment optimized and preventing mailboxes from reaching their storage limits. One of the best ways to do this is by archiving old emails that are no longer actively used but need to be retained for future reference. By automating the process of moving older emails into an archive folder, administrators can save time and ensure consistent mailbox management.

In this article, we’ll walk through a PowerShell script that leverages Microsoft Graph to archive emails older than a specified number of days for a particular user. This script will help administrators implement mailbox management policies with ease.

The Script: Archive Old Emails for a Specific User

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Mail.ReadWrite.All"

# Define the user whose old emails you want to archive
$UserId = "user@yourdomain.com"

# Define the number of days after which emails should be archived (e.g. 30 days)
$days = 30
$archiveThreshold = (Get-Date).AddDays(-$days).ToString("yyyy-MM-ddTHH:mm:ssZ")

# Retrieve old emails (older than the specified days) from the user's inbox
$oldEmails = Get-MgUserMessage -UserId $UserId -Filter "receivedDateTime lt $archiveThreshold" -Property Id Subject ReceivedDateTime

# Ensure the Archive folder exists or create it
$archiveFolder = Get-MgUserMailFolder -UserId $UserId -Filter "displayName eq 'Archive'"
if (-not $archiveFolder) {
    $archiveFolder = New-MgUserMailFolder -UserId $UserId -DisplayName "Archive"
}

# Move old emails to the Archive folder
foreach ($email in $oldEmails) {
    Move-MgUserMessage -UserId $UserId -MessageId $email.Id -DestinationId $archiveFolder.Id
    Write-Host "Archived email: $($email.Subject)"
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph

How the Script Works

  • Connect-MgGraph: The script starts by connecting to the Microsoft Graph API with the permission scope Mail.ReadWrite.All allowing full access to the user's mailbox including reading, writing, and moving messages.
  • User Definition: The script defines the UserId, which refers to the user’s email address (User Principal Name) of the mailbox that needs to be managed. You can modify this value to target any user.
  • Archive Threshold: The $days variable is used to specify the age of the emails to be archived. The script calculates the archive threshold by subtracting the specified number of days (30 days in this example) from the current date.
  • Retrieve Old Emails: Using the Get-MgUserMessage cmdlet, the script retrieves all emails that are older than the specified number of days from the user’s inbox. It filters the emails based on the receivedDateTime property and only retrieves the required fields like Id, Subject, and ReceivedDateTime.
  • Check or Create Archive Folder: The script checks whether an "Archive" folder exists in the user’s mailbox using the Get-MgUserMailFolder cmdlet. If it doesn’t exist, the script creates one using the New-MgUserMailFolder cmdlet.
  • Move Emails to Archive: The Move-MgUserMessage cmdlet is used to move each of the retrieved old emails into the "Archive" folder. For every email moved, the script outputs the subject of the archived email for confirmation.
  • Disconnect-MgGraph: Finally, the script disconnects from Microsoft Graph ensuring that the session is properly terminated.

Further Enhancements

There are several ways to enhance this script to suit different organizational needs:

  • Archive Emails for Multiple Users: You can modify the script to loop through a list of users from a CSV file, allowing the script to archive old emails for multiple users at once.
  • $users = Import-Csv "C:\UsersList.csv"
    foreach ($user in $users) {
        $oldEmails = Get-MgUserMessage -UserId $user.UserPrincipalName -Filter "receivedDateTime lt $archiveThreshold"
        foreach ($email in $oldEmails) {
            Move-MgUserMessage -UserId $user.UserPrincipalName -MessageId $email.Id -DestinationId $archiveFolder.Id
            Write-Host "Archived email: $($email.Subject) for user: $($user.UserPrincipalName)"
        }
    }
  • Exclude Specific Email Types: You can enhance the filtering to exclude certain email types (e.g., exclude unread or flagged emails) by adding conditions to the -Filter parameter:
  • $oldEmails = Get-MgUserMessage -UserId $UserId -Filter "receivedDateTime lt $archiveThreshold and isRead eq true"
  • Send Summary Report: Add functionality to email a summary report to the administrator after the script has run, summarizing how many emails were archived per user.
  • $emailReport = "Archived $($oldEmails.Count) emails for $UserId"
    Send-MailMessage -To "admin@yourdomain.com" -Subject "Email Archive Report" -Body $emailReport -SmtpServer "smtp.yourdomain.com"

Possible Errors & Solutions

Error Cause Solution
Insufficient privileges The connected account doesn’t have the required API permissions. Ensure that the account has been granted Mail.ReadWrite.All permissions in Azure AD.
Move-MgUserMessage not recognized The Microsoft Graph PowerShell module may not be installed. Install the Microsoft Graph PowerShell module by running Install-Module Microsoft.Graph.
Archive folder not found There may be an issue with folder creation permissions or folder naming. Verify that the New-MgUserMailFolder cmdlet is functioning correctly.
No messages found to archive The filter might be too restrictive or the mailbox may not have any emails older than the defined threshold. Adjust the archive threshold or check the mailbox contents to ensure it contains messages.

Conclusion

Automating the archiving of old emails using Microsoft Graph PowerShell is a powerful way to manage mailbox sizes efficiently and ensure mailboxes don’t become cluttered. By moving older messages to an archive folder, administrators can maintain an organized mailbox environment and enforce retention policies effortlessly.

This script can be further customized to meet various business needs, such as applying the policy to multiple users or excluding certain types of emails. Explore the flexibility of Microsoft Graph PowerShell and start implementing automation that saves time and effort in your Microsoft 365 environment!

Suggested Reading

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