#!/usr/bin/env python
#
# Copyright (C) 2001,2002,2003 Jason R. Mastaler <jason@mastaler.com>
#
# This file is part of TMDA.
#
# TMDA is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.  A copy of this license should
# be included in the file COPYING.
#
# TMDA is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with TMDA; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

"""
Collect e-mail addresses from mailboxes of various formats.
Unix-style mbox files, qmail-style Maildirs, and MH/nmh-style folders
are supported.  Each unique address is printed to stdout in lowercase.

Every file or directory within the current working directory is
assumed to be in one of the supported mailbox formats.

Sample usage:

$ cd ~/Mail/archive/
$ collectaddys > ~/.tmda/lists/whitelist
"""

import mailbox
import os

# Collect addresses from these headers only; season to taste.
hdrs = [ 'from', 'return-path', 'sender' ]

uniq = {}

for path in os.listdir('.'):
    # If it's a directory, try to guess whether it's a Maildir or an
    # MH folder.
    if os.path.isdir(path):
        if os.path.isdir(os.path.join(path, 'cur')) and \
           os.path.isdir(os.path.join(path, 'new')) and \
           os.path.isdir(os.path.join(path, 'tmp')):
            mb = mailbox.Maildir(path)
        else:
            mb = mailbox.MHMailbox(path)
    # Otherwise assume a Unix-style mbox file.
    else:
        mb = mailbox.PortableUnixMailbox(open(path))
    while 1:
        msg = mb.next()
        if not msg:
            break
        else:
            for hdr in hdrs:
                if msg.has_key(hdr):
                    address = msg.getaddr(hdr)[1]
                    if address is not None:
                        address = address.lower()
                        uniq[address] = address
                    
for a in uniq.keys():
    if a:
        print a
