changeset 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
files emaildispatcher/handlers.py emaildispatcher/main.py setup.py
diffstat 3 files changed, 55 insertions(+), 11 deletions(-) [+]
line wrap: on
line diff
--- a/emaildispatcher/handlers.py	Wed Dec 30 22:46:56 2009 -0500
+++ b/emaildispatcher/handlers.py	Thu Dec 31 00:26:33 2009 -0500
@@ -1,3 +1,9 @@
+from datetime import datetime
+import base64
+import os
+
+timestamp = '%Y%m%d%H%M%s'
+
 class Images(object):
     "extract images from an email message"
     
@@ -5,5 +11,29 @@
         self.directory = directory
 
     def __call__(self, message):
-        import pdb; pdb.set_trace()
+        payload = message.get_payload()
+        if isinstance(payload, basestring):
+            if message.get_content_maintype() == 'image':
+                if message.get('Content-Transfer-Encoding') == 'base64':
+                    payload = base64.b64decode(payload)
+                filename = message.get_filename()
+                if filename is None:
+                    filename = datetime.now().strftime(timestamp)
+                    
+                if os.path.exists(os.path.join(self.directory, filename)):
+                    datestamp = datetime.now().strftime(timestamp)
+                    if '.' in filename:
+                        base, ext = filename.rsplit('.', 1)
+                        filename = '%s.%s.%s' % (base.rstrip('.'), datestamp, ext)
+                    else:
+                        filename = '%s.%s' % (filename, datestamp)
+                f = file(os.path.join(self.directory, filename), 'wb')
+                f.write(payload)
+                f.close()
+        else:
+            # assume a list of Messages
+            for part in payload:
+                self(part)
+        
+
     
--- a/emaildispatcher/main.py	Wed Dec 30 22:46:56 2009 -0500
+++ b/emaildispatcher/main.py	Thu Dec 31 00:26:33 2009 -0500
@@ -2,6 +2,7 @@
 
 import sys
 
+from email import message_from_string
 from email.Message import Message
 from optparse import OptionParser
 from pkg_resources import iter_entry_points
@@ -13,29 +14,42 @@
     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=[],
+    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)
 
-    vars = dict([arg.split('=, 1) for arg in args if '=' in arg])
+    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]
 
-    handlers = {}
-    for handler in iter_entry_point('email.dispatchers'):
-        import pdb; pdb.set_trace()
+    handler = handlers[options.handler](*args, **kwargs)
 
-    if options.from:
-        input = file(options.from).read()
+    if options.file:
+        input = file(options.file).read()
     else:
         input = sys.stdin.read()
 
-    message = Message(input)
-
+    message = message_from_string(input)
+    handler(message)
     
 
 if __name__ == '__main__':
--- a/setup.py	Wed Dec 30 22:46:56 2009 -0500
+++ b/setup.py	Thu Dec 31 00:26:33 2009 -0500
@@ -26,6 +26,6 @@
       emaildispatcher = emaildispatcher.main:main
 
       [email.dispatchers]
-      extract_images = emaildispatcher.dispatchers:Images
+      extract_images = emaildispatcher.handlers:Images
       """,
       )