As I said before mocking Google for the lack of a Gmail API, we’re forced to turn to IMAP. This being an exercise in python, I turned to the standard library docs, and got no help … worse than no help, confusing ‘help’. Next up, I think we should repent and turn to Google to help us find example code that will show us the proper way to deal with imaplib.
To summarize the results … crap. Some decent attempts, but mostly, as you can see in my references, crap. Don’t trust my opinion? Fine, I never liked you anyway … here’s a quote from the ActiveState IMAP MailWatcher recipe:
rough edges. The [example] code is organized in an awkward way. Presentation does not cleanly separate from the core code. This showed painfully when I wanted to deploy this recipe on a box where tcl/Tk was not available. Thus I wanted to replace Tkinter calls so that simply an external program gets called if there is a new mail. Ideally, this should be the matter of replacing a presentation class or function call with another one, leaving IMAP related code intact. But the Mailwatcher class just blends everything together with no concern, so I had to actually understand the IMAP code to achieve what I want, and alltogether [sic], work more on it.
Harsh, but fair. I hope that I acquit myself better. Code follows.
01/30/09 – Also found, webpymail which seems to be a similar idea. But also in a fairly beta format.
To start with, we need a manager class to abstract away everything but our logical thoughts of what a mailbox system should be:
a mailserver, a list of mailboxes, and a list of messages. Anything more than that, and well, I get *gosh darn* confused.
#imap_gmail.py import imaplib import gmail_mailboxes, gmail_messages, gmail_message class gmail_imap: def __init__ (self, username, password): self.imap_server = imaplib.IMAP4_SSL("imap.gmail.com",993) self.username = username self.password = password self.loggedIn = False self.mailboxes = gmail_mailboxes.gmail_mailboxes(self); self.messages = gmail_messages.gmail_messages(self); def login (self): self.imap_server.login(self.username,self.password) self.loggedIn = True def logout (self): self.imap_server.close() self.imap_server.logout() self.loggedIn = False
All of the above is reasonably self explanatory, except for self.loggedIn which just holds the current state of our object so that we don’t need to do any crazy testing to know if we’re logged in or not.