PHP Script to trim IMAP Mailbox (e.g. trash)

Line Break

Author: Mohannad Hussain (9 Articles)

Hello, my name is Mohannad! I am a Zend certified PHP 5 engineer, but I am also interested in Javascript, Java, mobile development (native & web), Linux & shell scripting plus User experience & interface.

I am lazy! Wait, that came out wrong. I like efficiency and automating things, and I am notorious for having scripts for anything and everything. Well, today, I have a new one to share with you.

I know most people these days use things like Gmail, but I am old fashioned and still like to own my own data, which is why I stick with IMAP. The problem with that, is that searching can get a little slow, or even time out on folders that might get a little too big.

For example, occasionally I’ll need to go and search for something in my “Trash” folder, but the search times out because of the thousands of messages I have there. The reality is, I only need messages going back about a month or so, if I only I could something that would automatically purge anything older than, say, 30 days…. I could not find anything, so I wrote my own PHP script, ready to run as cron job.

The script takes configuration parameters for:

  • IMAP server hostname (or IP) and port
  • Mailbox username and password
  • The folder of interest (e.g. Trash, Sent…etc)
  • Threshold for keeping messages newer than X days, which defaults to 30.

This is exactly what the script does:

  1. Connect to IMAP server
  2. Find the exact path of the target folder (e.g. Trash)
  3. Loop through all the messages in that folder
  4. Examine the date on each message, if older than threshold (e.g. 30 days) then delete, otherwise move on
  5. Purge deleted message (aka expunge in IMAP terminology) and disconnect

If you capture the output of the cron (e.g. have it emailed to you), then you’ll get a list of deleted messages and/or any errors encountered (if any).

View the PHP source code of the IMAP mailbox trimning cron script – Enjoy!