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:
- Connect to IMAP server
- Find the exact path of the target folder (e.g. Trash)
- Loop through all the messages in that folder
- Examine the date on each message, if older than threshold (e.g. 30 days) then delete, otherwise move on
- 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).