How to Purge all mailboxes on your cPanel server

These days IMAP is the standard email protocol used to manage an email account but what some don't know is that when you delete a message it's not actually removed until that mailbox is “purged”. Many email clients will do this automatically but there are some that won't and will require the user to purge the account manually.

The following script was created to purge any deleted mail from all mailboxes on a cPanel server.

#!/bin/bash
 
# Account list
accounts=$(whmapi1 listaccts --output=yaml 2>/dev/null | grep 'user: ' | sed 's/user: //g' | sed 's/ //g')
 
for account in $accounts; do
    mailboxes=$(uapi --user ${account} Email list_pops 2>/dev/null | grep 'email: ' | sed 's/email: //g' | sed 's/ //g')
 
    for mailbox in $mailboxes; do
        echo -n "Purging mailbox ${mailbox}..."
        doveadm purge -u ${mailbox}
        echo "Done"
    done
done

Please note that this script only purges email in the users INBOX and will not purge email in any sub folders