Listing IMAP Mailboxes with Python

|

I’ve been working on some Python scripts recently to manage my IMAP mailboxes and the information I found on the internet was fairly good, but lacked a completeness that my newbie Python skills required. So, I figured I’d post a complete example to list mailboxes (folders) for your IMAP account. This was developed using Python 3.3.

import imaplib
import sys
import traceback

# Your IMAP Settings
host = ''
port = 143
user = ''
password = ''

imap = None

'''
parse_mailbox() will extract the three pieces of information from
the items returned from a call to IMAP4.list(). The initial data
array looks like:
[b'(\\HasChildren) "/" NameOfFolder', ...]
At least on my server. If the folder name has spaces then it will
be quote delimited.
'''
def parse_mailbox(data):
    flags, b, c = data.partition(' ')
    separator, b, name = c.partition(' ')
    return (flags, separator.replace('"', ''), name.replace('"', ''))

try:
    # Create the IMAP Client
    imap = imaplib.IMAP4(host, port)
    # Login to the IMAP server
    resp, data = imap.login(user, password)
    if resp == 'OK' and bytes.decode(data[0]) == 'LOGIN completed':
        # List all mailboxes
        resp, data = imap.list('""', '*')
        if resp == 'OK':
            for mbox in data:
                flags, separator, name = parse_mailbox(bytes.decode(mbox))
                fmt = '{0}    : [Flags = {1}; Separator = {2}'
                print(fmt.format(name, flags, separator))
except:
    print('Unexpected error : {0}'.format(sys.exc_info()[0]))
    traceback.print_exc()
finally:
    if imap != None:
        imap.logout()

I hope this code snippet help you on your way to Python IMAP goodness. If not, it will at least server as a reminder to myself the next time I need to do something like this.