#!/usr/bin/env python
# Copyright (C) 2004  Scott James Remnant <scott@netsplit.com>

# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
# ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


import email
import email.Errors
import mailbox
import re, sys

from email.Utils import parsedate_tz, mktime_tz

def print_mail(mail):
    for hdr in ( 'from', 'to', 'date', 'subject' ):
        if hdr in mail:
            print "%s: %s" % (hdr.capitalize(), mail[hdr])
    print

    first = True
    for part in mail.walk():
        if not first: print "-" * 20

        if part.get_content_type() == "text/plain":
            print part.get_payload(decode=True),
            first = False
        elif part.get_content_maintype() != "multipart":
            print "Attachment:"
            print "Content-Type:", part.get_content_type()
            if part.get_filename():
                print "Filename:", part.get_filename()
            first = False


def read_mbox(filename):
    first = True

    mb = open(filename)
    mbox = mailbox.UnixMailbox(mb, email.message_from_file)

    def strip_re(subject):
        return re.sub("^Re:\s*", "", subject)

    def sort_mails(a, b):
        # Sort by Subject: as well
        #ret = cmp(strip_re(a['subject']), strip_re(b['subject']))
        #if ret: return ret

        a_time = mktime_tz(parsedate_tz(a['date']))
        b_time = mktime_tz(parsedate_tz(b['date']))
        return cmp(a_time, b_time)

    mails = list(mbox)
    mails.sort(sort_mails)
    for mail in mails:
        if not first:
            print "-" * 76
            print
        first = False

        print_mail(mail)
    mb.close()


if __name__ == "__main__":
    if len(sys.argv) == 1:
        print "Usage: %s <mbox filename>" % sys.argv[0]
        sys.exit(1)
    for filename in sys.argv[1:]:
        read_mbox(filename)

