11.7.2 IMAP4 Example

Here is a minimal example (without error checking) that opens a mailbox and retrieves and prints all messages:

import getpass, imaplib, string
M = imaplib.IMAP4()
M.LOGIN(getpass.getuser(), getpass.getpass())
M.SELECT()
typ, data = M.SEARCH(None, 'ALL')
for num in string.split(data[0]):
    typ, data = M.FETCH(num, '(RFC822)')
    print 'Message %s\n%s\n' % (num, data[0][1])
M.LOGOUT()

Note that IMAP4 message numbers change as the mailbox changes, so it is highly advisable to use UIDs instead, with the UID command.

At the end of the module, there is a test section that contains a more extensive example of usage.

See Also:

Documents describing the protocol, and sources and binaries for servers implementing it, can all be found at the University of Washington's IMAP Information Center (http://www.cac.washington.edu/imap/).