IMAP4 and Python

Python’s IMAPv4 client library imaplib is a really light-weight wrapper over the IMAP4 protocol. As such, it isn’t that intuitive to use. The best reference I’ve found on it is a cheat-sheet over here.

Basic usage is to create a IMAP connection object, using the imaplib.IMAP4() or imaplib.IMAP4_SSL() functions. Login to the server. You then select() a mailbox and search() within it to retrieve messages. If the search was successful, it will return a tuple with the first element being “OK”, and the second element is an array with the first item being a list of matching message identifiers. Each identifier can be passed to the fetch() command.

Search queries look like '(FROM "person@server.com) (SUBJECT "Coolio")'. You can also use ALL, OR, and NOT operators.