As Exchange Online admins, there are various reasons we may want to remove a mail from one of our users mailboxes. We may want to remove a specific Phishing mail, or a sensitive mail that was sent to the wrong person. To do this, we can create a new content search and delete the results, this works fine on most occasions, however this can be a slow process and is also limited to 10 items per mailbox. When we want to rapidly remove a single mail or group of mails more quickly, we can use Graph API. I’ve created this script to allow us to select one or more mails from a particular mailbox and delete them immediately.
Preparing the environment
As with all of my Graph scripts, I use an application registration to authenticate and grant permissions for the task. For this script, set up a new App Reg as per ‘Tip 1’ in this post. The permissions required are the ‘Mail.ReadWrite’ (Figure 1) application permissions. Take note of the Application ID, Directory ID and Application Secret as per ‘Tip 3’ in the same post.
Running the Script
To run the script, download it from GitHub and run with the following parameters.
- Mailbox – The User Principal Name of the target mailbox
- StartDate – The date/time to start the search from (in the format dateTime)
- EndDate – The date/time to end the search from (in the format dateTime)
- ClientID – The Application (Client) ID from the App Reg
- TenantID – The Directory (Tenant) ID from the Tenant
- ClientSecret – The Client Secret from the App Reg
.\graph-DeleteTargetedMail.ps1 -Mailbox "email@example.com" -ClientSecret $clientSecret -ClientID $clientID -TenantID $tenantID -StartDate "2021-01-30T00:00:00Z" -EndDate "2021-06-01T00:00:00Z"
Once the script starts and searches the mailbox, the results will be shown as a Grid View. Select one or more (by holding CTRL) mails from the Grid View window as seen in Figure 3, and click “OK” to begin the delete.
The script will then ‘delete’ all of the selected mails by moving them to the ‘Purges’ folder which is invisible to the end user. The mails will be fully deleted the next time the mailbox assistant runs. The mails can still be recovered by an admin up until this point. You will also see an output of the deleted item as it is processed (Figure 4).
This script is a very powerful tool to quickly remove mails from mailboxes. It can also be modified to perform the deletion task on multiple mailboxes at once. As with any script, please make sure to read, understand and test the script before running in a production environment, particularly when deletions are involved.
The script is available in my GitHub repository.