The state of IMAP access in the main python library is appalling. I don’t mean poor quality so much as thin; the documentation is thin, the examples are thin, and the code itself is a thin layer of sugar over the raw strings being burped out by the IMAP server. I know I can’t fix it, because well, no one cares, but I can show you how I’ve gotten it working with gmail.
Maybe IMAP is falling out of vogue and no one told me, or perhaps anyone interested just uses java, I dunno. But I do know that I want to use it to access gmail rather than trying to use the various silly hacks ( *cough* gmail.py *cough* ) that break whenever gmail decides to piss on a dog. And it’s a pain in the ass. Not because of gmail’s strange implementation of IMAP (that’s a different rant) but because … it’s just thin.
Let’s look at the ‘example’ code from Python IMAPLib:
import getpass, imaplib M = imaplib.IMAP4() M.login(getpass.getuser(), getpass.getpass()) M.select() typ, data = M.search(None, 'ALL') for num in data.split(): typ, data = M.fetch(num, '(RFC822)') print 'Message %s\n%s\n' % (num, data) M.close() M.logout()
Very readable isn’t it, nice descriptive variable names? Wait … you say you can’t magically divine what M is? Oh well, that’s obviously the ‘M’ailsever … I mean ‘M’ailbox. Ok, so at least data is clear, well, wait what is ‘typ’? Wait … data is used again … what the hell … this is an example? Yes, of unreadable programming. Incidentally, this is the longest of the three whole examples on that page.
Here’s what I’d prefer (and what I’ll talk about in the next post):
gmail = gmail_imap("email","pass") gmail.mailboxes.load() print gmail.mailboxes #List my gmail mailboxes gmail.messages.process("INBOX") print gmail.messages # List my mail subject lines # and enough info to find a message message = gmail.messages.read(gmail.messages[unique_id:1]) print message.textContent # Print the text content of the message gmail.logout()