Counting Messages in IMAP Folders in Python


Continuing on my last post (), I wanted to show a snippet of Python code that will list a set of IMAP folders and count the number of messages in them. You give it a starting folder and it lists that folder plus all/any sub-folders and their message counts. At the very end it prints a total message count.

from imaplib import IMAP4, IMAP4_PORT
import sys, traceback

# Your IMAP Settings
host = ''
port = IMAP4_PORT
user = ''
password = ''
folder = 'INBOX'

imap = None

def parse_mailbox(data):
    flags, b, c = data.partition(' ')
    separator, b, name = c.partition(' ')
    return (flags, separator.replace('"', ''), name.replace('"', ''))

    # Create the IMAP Client
    imap = IMAP4(host, port)
    # Login to the IMAP server
    resp, data = imap.login(user, password)
    if resp == 'OK' and bytes.decode(data[0]) == 'LOGIN completed':
        totalMsgs = 0
        # Get a list of mailboxes
        resp, data = imap.list('"{0}"'.format(folder), '*')
        if resp == 'OK':
            for mbox in data:
                flags, separator, name = parse_mailbox(bytes.decode(mbox))
                # Select the mailbox (in read-only mode)
      '"{0}"'.format(name), True)
                # Get ALL message numbers
                resp, msgnums =, 'ALL')
                mycount = len(msgnums[0].split())
                totalMsgs = totalMsgs + mycount
                print('{:<30} : {: d}'.format(name, mycount))
            print('{:<30} : {: d}'.format('TOTAL', totalMsgs))
    print('Unexpected error : {0}'.format(sys.exc_info()[0]))
    if imap != None:
    imap = None