author | Alberto Bertogli
<albertito@blitiri.com.ar> 2010-05-02 20:05:39 UTC |
committer | Alberto Bertogli
<albertito@blitiri.com.ar> 2010-05-03 07:11:30 UTC |
sea | +60 | -0 |
diff --git a/sea b/sea new file mode 100755 index 0000000..ed85d52 --- /dev/null +++ b/sea @@ -0,0 +1,60 @@ +#!/usr/bin/env python + +""" +Save Email Attachments + +Read an email from stdin, save the attachments to the directory given as the +first parameter. +""" + +import sys +import email +import mimetypes +import os +import time + + +def main(infd, basepath): + m = email.message_from_file(infd) + + f_name, f_email = email.Utils.parseaddr(m['from']) + subject = m['subject'] + + if not m.is_multipart(): + # no attachments + return 0 + + # put the attachments in basepath/<from>-<time> + outpath = "%s/%s~%s/" % (basepath, f_email.replace('/', ''), + time.strftime("%Y-%m-%d-%H:%M:%S")) + + if not os.path.exists(outpath): + os.mkdir(outpath) + + count = 0 + for part in m.walk(): + count += 1 + + if part.is_multipart(): + # we will see the individual parts later + continue + if part.get_content_maintype() == 'text': + # text is not interesting + continue + + fname = part.get_filename('') + if not fname: + ext = mimetypes.guess_extension( + part.get_content_type() ) + fname = 'att-%d.%s' % (count, ext) + fname = fname.replace('/', '') + + # since it's not multipart (checked earlier), we know this is + # the proper payload content + p = part.get_payload(decode = True) + open(outpath + '/' + fname, 'w').write(p) + + +if __name__ == '__main__': + sys.exit(main(sys.stdin, sys.argv[1])) +