Brool brool (n.) : a low roar; a deep murmur or humming

Creating Mail Digests with Python and IMAP

 |  python coding imap

There should be a word for “effort undertaken even though you’re sure, somewhere, somebody has written something for it already, or maybe it’s already a Linux command.” I get the distinct feeling that this utility already exists, but I googled to no avail.

I have a bunch of e-mail boxes, some incredibly infrequently used, but I wanted to be sure that I noticed any important messages without having to go to all the work of, you know, actually logging into them. So I created a quick little digest utility that will on a daily cron.

This entire process was about two times more painful than it really needed to be because using the IMAP libraries in Python really requires knowing the IMAP specification, and I tried to be lazy and not bother reading the specification first, so I got stuck for a bit on how to search an IMAP mailbox properly.

TL;DR Version

You see,, 'ALL') was working fine, but I wanted to get all of yesterday’s messages. It turns out that instead of using:, 'SINCE 1-Dec-2008')

you just need to have every token be a separate parameter:, 'SINCE', '1-Dec-2008')

…which seems unpythonic to me, but no matter.

Testing From The Console

It helped me to be able to interact with the IMAP servers from the command line. Usually, I just use telnet to do this, but the IMAP servers that I was working with were SSL only. There’s an easy way to deal with this, at least under Debian; just install the telnet-ssl package and then log into it like:

telnet-ssl -z ssl

IMAP takes arbitrary sequence IDs at the start of every command. The starting login sequence is something like:

0001 LOGIN userid password 0002 SELECT INBOX 0003 SEARCH SINCE 27-Dec-2008

Turning On Debug Information

Alternatively, you can just turn on the debug information for the IMAP libraries, by doing something like:

imaplib.Debug = 99
imap = imaplib.IMAP4_SSL("")

… and then go through the standard sequence.

Code can be found on github.


Comments are moderated whenever I remember that I have a blog.

sebp999 | 2010-03-02 16:26:34
Aha the imaplib docs are wrong! That sorts it! Thank you!
Wayne | 2010-03-23 16:45:28
Ok, seriously you just saved me a bunch of work. I had the EXACT same feeling as you, it had to be out there... somewhere. I searched and searched... and finally you were result #3 for "python email fetch all mail since yesterday" Thanks for sharing!
Add a comment