Mass delete email (or any files) over SSH

I get a lot of automated mail that I do need for analysis, but it can be a pain to delete it all.

Admittedly, if I set filters better it would be easier, but even so, if you have thousands of emails in a folder and you need to delete them using webmail remotely, it is time consuming.

So let’s do it with SSH.

WARNING. This shit is dangerous. If any of this doesn’t make sense DON’T DO IT!

Login to your server via SSH

Change to your mail dir (this is the location on my CentOS 5 box)
Note the mail address format – @ is escaped with , period are replaced with underscores:

$ cd /home/{domain username}/mail/.{user@domin_tld}/{folder}/

If you are cleaning your inbox the folder is


Test the message selection before you delete!
I’m deleting Cron messages from a server. The message source for these all contain ‘Subject: Cron <user@server>’ (I’ve anonymised the server address)
Note the search is regex, so special chars must be escaped

$ grep -l 'Subject: Cron <user@server>' * > grep.txt

Then I open the grep.txt file, copy some filenames and then open those files to double check I’m selecting the right messages.

Once I’m satisfied I’m not selecting anything I shouldn’t:

$ grep -l 'Subject: Cron' * | xargs rm -f

Shazzam. From >3000 emails to 150 in two minutes. I should probably check that account more often…