Page 1 of 1

Howto: dovecot expunge spam/trash

Posted: Wed Mar 07, 2018 1:23 pm
by GuzziGuy
On another (non-Vesta) mail server I run, I these daily cron tasks:

Code: Select all

0 3 * * * doveadm expunge -A mailbox Trash savedbefore 30d
5 3 * * * doveadm expunge -A mailbox Junk savedbefore 30d
To save space by clearing out trash and junk older than 30 days. Note the -A flag does this for all users - but on a Vesta server, this doesn't work - because the config is split among different domain-specific files, dovecot doesn't 'know' all the users.

Instead I came up with this script - couldn't see anything similar on the forum, so hope this helps some folks:

Code: Select all

#!/bin/bash

#run this so cron job has environment variable
export VESTA='/usr/local/vesta'

#can't force everyone to use the same folders, so catch both variants
declare -a dcfolders=( "Trash" "Spam" "Junk" "Deleted Messages" )

sudo /usr/local/vesta/bin/v-list-users plain | cut -f1 | sort | while read -r vuser ; do
    sudo /usr/local/vesta/bin/v-list-mail-domains $vuser plain | cut -f1 | sort | while read -r vdomain ; do
        sudo /usr/local/vesta/bin/v-list-mail-accounts $vuser $vdomain plain | cut -f1 | sort | while read -r vaccount ; do
    	    for dcfolder in "${dcfolders[@]}"
	        do
      	        if sudo doveadm mailbox list -u $vaccount@$vdomain | grep "^${dcfolder}$" > /dev/null;
    	        then
                    echo  "$vaccount@$vdomain $dcfolder"
                    sudo doveadm -v expunge -u $vaccount@$vdomain mailbox "$dcfolder" sentbefore 30d
	            fi
	        done

        done
    done
done
You can add this to your admin cron. Just, I think, one prerequisite:
  • You'll need to edit sudoers to allow admin to sudo doveadm without a password (my route)
  • Or, I think you may be able to add admin to the mail group, and change the script to run doveadm without sudo
  • Or remove all sudo references and add it to your sudo crontab
/etc/sudoers.d/admin - amend the following:

Code: Select all

admin   ALL=NOPASSWD: /usr/local/vesta/bin/*, /usr/bin/doveadm
NB suggest having an alternative sudo (or root) login when mucking about with sudoers.d - any mistakes and you may not be able to sudo to undo them!

Re: Howto: dovecot expunge spam/trash

Posted: Fri Jul 19, 2019 4:26 pm
by Elfy
This is great work, thank you! Works perfectly for me 1 year later.