The first article in this series discussed how to access a POP3 server with a Python script. While that protocol is useful for learning the basics of how email works, IMAP is the protocol most used today. This article covers this more complicated protocol.
In the previous article from this series, I described how to access a POP3 server with a Python script. While POP is a useful protocol for connecting to legacy servers and gaining a basic understanding of how email works, IMAP is the workhorse protocol for email today. IMAP is designed for users to store their email remotely on the server, rather than locally on their own server. It also allows for users to create a folder system in their inbox to organize and move messages around the mailbox. This all makes IMAP a much more complicated protocol than POP, which in turn translates to a more complicated library in Python.
Much of the IMAP library in Python is very closely tied to the actual IMAP protocol definition in RFC 2060. When you are working with this library, both the Python docs and that RFC are necessary references, as very often arguments to functions will need to be formatted as this RFC states, and responses will be returned in the format defined by that RFC.
Connecting to the Server
Again, the first task you’ll need to accomplish when working with an IMAP server is creating the IMAP object to communicate with the server:
from imaplib import *
…
server = IMAP4(“test.com”)
The objects necessary to work with IMAP servers are held in the “imaplib” library so it must be imported first. The library itself also contains a few other useful objects. First of all, there are two exception classes, “error” and “abort.” The “error” exception generally denotes some sort of failure on the client’s part, and the reason for that error is passed along with the exception. The “abort” exception usually results from some server-side error, and the connection must usually be reset to recover from this error. In addition, “imaplib” also contains several functions that can come in handy, for converting dates into the format used by IMAP and for parsing some IMAP server responses.