Perl: Archive E-Mails in an IMAP Folder

IMAP folders are really because you can have your e-mails synchronized on multiple devices, without losing e-mails across your devices when retrieving your new e-mails. IMAP folders actually also aren’t that cool because e-mails are usually never deleted or even archived. Having millions of e-mails can make some e-mail readers on certain devices really slow.

The below script is an example how to clean and archive e-mails. The script was written in Perl and tested on a Courier IMAP server. Remember the Perl devise: there are million ways to write Perl scripts.

The following modules were used:

The configuration file is written in YAML and the logging of the script is handled by Log4Perl.

The configuration file contains the login credentials and the threshold values:

The threshold values are in fact the same parameters that can be used in the DateTime method ‘subtract()’;

The main loop of the program will:

  • Connect to the IMAP server
  • Retrieve all IMAP folders and loop through them
  • Loop through all messages in each mailbox

Let’s go through the different subroutines called in the mainloop.

connect_imap()

The parameters expected in the ‘$cfg’ hash are:

  • host
  • user
  • pass

get_mailboxes()

Ok, I admit, I shouldn’t have created an extra subroutine for it… but i was kind of in a flow!

get_mail_header()

This subroutine takes the ‘$imap’ object and the message number as input parameters. It will then retrieve the mail header and convert it to an ‘Email::Simple’ object. I’ve chosen this module so I can easily extract header fields.
If no ‘Date:’ field was found in the e-mail, then the tool will just delete the email. I don’t like e-mails with wrong or missing headers 😉 (they’re usually spam anyway).

delete_mail()

Pretty straightforward.

get_archive_box()

This subroutine will assemble the archive mailbox name. It will then check if the mailbox already exists and otherwise create it and subscribe to it.

create_mailbox()

It will basically just create the mailbox and log about it.

subscribe()

move_mail()

Moving an e-mail consists of copying it first to the new mailbox and then afterwards removing it from the old mailbox.

And that’s basically it!


Comments

Perl: Archive E-Mails in an IMAP Folder — 1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *