IMAPClient

Easy IMAP for Python

Menno Smits
http://imapclient.freshfoo.com/

What is IMAP?

On the wire 1

S: * OK Dovecot ready.
C: a1 LOGIN MyUsername MyPassword
S: a1 OK Logged in.
C: a2 LIST "" "*"
S: * LIST (\HasNoChildren) "." "INBOX"
S: a2 OK List completed.
C: a3 SELECT INBOX
S: * FLAGS (\Answered \Flagged \Deleted \Seen \Draft)
S: * 1 EXISTS
S: * 1 RECENT
S: * OK [UNSEEN 1] First unseen.
S: * OK [UIDVALIDITY 1257842737] UIDs valid
S: * OK [UIDNEXT 2] Predicted next UID
S: a3 OK Select completed.
          

On the wire 2

C: a4 FETCH 1 BODY[]
S: * 1 FETCH (BODY[] {199}
S: Return-Path: sender@example.com
S: From: sender@example.com
S: Subject: Test message
S: To: recipient@example.com
S: Message-Id: <20040120203404.CCCC18555.mx1.example.com@C.example.com>
S:
S: This is a test message.
S: )
S: a4 OK Fetch completed.
C: a5 LOGOUT
S: * BYE Logging out
S: a5 OK Logout completed.
          

List of message ids - imaplib


            server = imaplib.IMAP4_SSL("some.where")
            resp, data = server.login("username", "sekrit")
            if resp != "OK":
                raise IOError("login failed: " + data[0])
            resp, data = server.select("INBOX")
            if resp != "OK":
                raise IOError("select failed: " + data[0])
            resp, data = server.uid("SEARCH", "NOT DELETED")
            if resp != "OK":
                raise IOError("search failed: " + data[0])
            # data will look something like: ["1 2 23"]
            messages = [int(m) for m in data[0].split()]
          

List of message ids - IMAPClient


            server = imapclient.IMAPClient("some.where", ssl=True)
            server.login("username", "sekrit")
            server.select_folder("INBOX")
            messages = server.search(["NOT DELETED"]) # e.g. [1, 5, 23]
          

Fetching messages - imaplib


              resp, data = server.fetch(1, "(INTERNALDATE BODY RFC822)")
              if resp != "OK":
                raise IOError("fetch failed: " + data[0])
          

            ('OK', [('1 (
                INTERNALDATE "10-Mar-2014 18:23:04 -0400"
                BODY (("TEXT" "PLAIN" ("CHARSET" "ISO-8859-1") NIL NIL "7BIT" 1316 47)("TEXT" "HTML" ("CHARSET" "ISO-8859-1") NIL NIL "QUOTED-PRINTABLE" 2163 48) "ALTERNATIVE")
                RFC822 {5759}',
                'Return-Path: <foo@bar.com>\r\nX-Original-To: menno@freshfoo.com\r\n...'),
            ')'])
          

Fetching messages - IMAPClient


              msgdata = server.fetch(1, ["INTERNALDATE", "BODY", "RFC822"])
          

{1: {
     'BODY': ([('TEXT', 'PLAIN', ('CHARSET', 'ISO-8859-1'), None, None, '7BIT', 1316, 47), ('TEXT', 'HTML', ('CHARSET', 'ISO-8859-1'), None, None, 'QUOTED-PRINTABLE', 2163, 48)], 'ALTERNATIVE'),
     'INTERNALDATE': datetime.datetime(2014, 3, 11, 11, 23, 4),
     'RFC822': 'Return-Path: <foo@bar.com>\r\nX-Original-To: menno@freshfoo.com\r\n...',
     'SEQ': 1
    }
}