Because my job needed something like this, I created a Python script that'll connect to an IMAP server, get all the emails, and then calculate the very rough daily average of emails received to the Inbox (as well as the 'smallest' number of emails handled per day, and the 'largest' number of emails handled per day, for the mailbox).  It's only designed to base the numbers off of existing emails in the inbox, not deleted items.  This is fine, since we don't delete anything in the inbox.The inbox is the only mailbox used, because it's a listserv mailbox, so it's not necessary to worry about the other mail boxes.  (The IMAP backend is dovecot.)The script allows for you to pass in arguments for its connection data, or if you don't it will prompt you for those items that it needs.  (IMAP server, IMAP login username/mailbox, IMAP password).  This relies on argparse for arguments processing.My only concern is that to gather the dates and do daily statistics, it has to pull every email in the inbox down for analysis.  This is going to be evil when run on a mailbox with hundreds, or even thousands, of emails.  My main concern is whether there's any way to optimize this, because I don't want to be slamming fetch requests to the IMAP server and flood the connection or lag out the IMAP process.mailbox_daily_average.py:#!/usr/bin/pythonimport imaplibimport datetimeimport emailimport sysimport argparsedef _get_arguments():    # Argument Parser    parser = argparse.ArgumentParser(        description=Run daily average stats for an IMAP mailbox., add_help=False)    parser.add_argument('--server', default=None, help=Mail server to use)    parser.add_argument('--username', '--mailbox',                        default=None,                        help=Mailbox to run stats on)    parser.add_argument('--password',                        default=None,                        help=Login password for mailbox)    return parser.parse_args()def main():    imap_messages_by_date = {}    args = _get_arguments()    imap_server = args.server    imap_user = args.username    imap_password = args.password    # This section handles interactive obtaining of connection details, if none are provided.    if args.server is None:        imap_server = str(raw_input(Please specify the IMAP server: ))    if args.username is None:        imap_user = str(raw_input(Please specify the IMAP username or mailbox to check: ))    if args.password is None:        imap_password = str(raw_input(Please enter the password for the IMAP mailbox: ))    try:        imap_conn = imaplib.IMAP4_SSL(imap_server, 993)        imap_conn.login(imap_user, imap_password)        imap_conn.select(INBOX, True)        rv, data = imap_conn.search(None, ALL)        if rv != 'OK':            print No Messages!            sys.exit(0)        for num in data[0].split():            rv, msgdata = imap_conn.fetch(num, '(RFC822)')            if rv != 'OK':                print ERROR getting message , num            msg = email.message_from_string(msgdata[0][1])            date_tuple = email.utils.parsedate_tz(msg['Date'])            if date_tuple:                local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))                datestamp = local_date.strftime('%Y-%m-%d')                try:                    imap_messages_by_date[datestamp] += 1                except KeyError:  # Doesn't exist in system yet                    imap_messages_by_date[datestamp] = 1        # for key, value in IMAP_MESSAGES_BY_DATE.iteritems():        #     print Date: %s    ||    Count: %s % (key, value)        dates_count = 0.0  # Init this here        messages_total_count = 0.0  # Init this here        for key, value in imap_messages_by_date.iteritems():            dates_count += 1            messages_total_count += value        max_emails_per_day = max(imap_messages_by_date.itervalues())        min_emails_per_day = min(imap_messages_by_date.itervalues())        rough_daily_average = messages_total_count / dates_count        print Min Mails Per Day (So Far): %s % min_emails_per_day        print Max Mails Per Day (So Far): %s % max_emails_per_day        print (Rough) Daily Mail Average: , rough_daily_average    except Exception as error:        print An error has occurred, and the program has crashed; details:\n        print str(error)        sys.exit(10)if __name__ == __main__:    main()
IMAP Mailbox Daily Average Volume Statistics Generator
python;performance;python 2.7;email;statistics