view emaildispatcher/main.py @ 1:2c76525ce80b

demo works: can be used to extract images to a directory
author k0s <k0scist@gmail.com>
date Thu, 31 Dec 2009 00:26:33 -0500
parents bbcc528508f1
children 5559e0734c8c
line wrap: on
line source

#!/usr/bin/env python

import sys

from email import message_from_string
from email.Message import Message
from optparse import OptionParser
from pkg_resources import iter_entry_points

def matches_from(message, accept_from):
    pass

def main(args=sys.argv[1:]):
    parser = OptionParser()
    parser.add_option('-f', '--file', dest='file',
                      help="file to read from (otherwise use stdin)")
    parser.add_option('-F', '--from', dest='From', default=[],
                      action='append',
                      help="from addresses to accept")
    parser.add_option('-H', '--handler', dest='handler', default=None,
                      help="handler to use")
    parser.add_option('--list-handlers', dest='list_handlers',
                      action='store_true', default=False,
                      help="list available handlers")
    options, args = parser.parse_args(args)

    handlers = {}
    for handler in iter_entry_points('email.dispatchers'):
        try:
            handlers[handler.name] = handler.load()
        except:
            pass

    if options.list_handlers:
        for handler in sorted(handlers.keys()):
            print handler
        sys.exit(0)

    assert options.handler

    kwargs = dict([arg.split('=', 1) for arg in args if '=' in arg])
    args = [arg for arg in args if '=' not in arg]

    handler = handlers[options.handler](*args, **kwargs)

    if options.file:
        input = file(options.file).read()
    else:
        input = sys.stdin.read()

    message = message_from_string(input)
    handler(message)
    

if __name__ == '__main__':
    main()