Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- import imaplib
- import datetime
- import email
- import sys
- import argparse
- def _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, data1 = imap_conn.fetch(num, '(RFC822)')
- if rv != 'OK':
- print "ERROR getting message ", num
- msg = email.message_from_string(data1[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()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement