#!/usr/bin/env python import email, sys, time, random, mimetypes, os, types """ Strip MIME attachments from an email when they are larger than MSG_MAX_SIZE, store them in MSG_DIR, and replace the MIME part with a link to MSG_URL, which should be a URL that exposes MSG_DIR. Example procmail recipe: MSG_MAX_SIZE=102400 MSG_URL=http://www.yourdomain.tld/mime/ MSG_DIR=/var/www/www.youdomain.tld/mime/. :0 fw * > $MSG_MAX_SIZE | $HOME/bin/mime_strip_to_dir.py """ def env_config(key, value): if os.environ.has_key(key): if type(value) == types.FloatType: return float( os.environ.get(key) ) if type(value) == types.IntType: return int( os.environ.get(key) ) return os.environ.get(key) return value MSG_MAX_SIZE = env_config("MSG_MAX_SIZE", 512 * 1024) MSG_URL = env_config("MSG_URL", "http://example.com/private/") MSG_DIR = env_config("MSG_DIR", "/var/www/example.com/web/private/.") email_file = sys.stdin if len( sys.argv ) > 1: email_file = open( sys.argv[1] ) def strip_to_dir(part, path): if part.get_content_maintype() == 'multipart': return filename = part.get_filename() if not filename: ext = mimetypes.guess_extension(part.get_content_type()) if not ext: ext = ".bin" filename = time.strftime("%Y%m%d-%H%M%S") + str(random.random()) + ext #filename = email_filename + '_' + msg['From'] fp = open( os.path.join( path , filename ), 'wb' ) fp.write(part.get_payload(decode=True)) fp.close() os.chmod( os.path.join( path , filename ) , 0644) url = MSG_URL try: part.replace_header('Content-Disposition', '') part.replace_header('Content-Type', 'text/plain') part.replace_header('Content-Transfer-Encoding', '7bit') except KeyError: pass part.set_payload(" Attachment saved to %(url)s%(filename)s " % locals()) return part def ignore_email(msg): print msg.as_string() sys.exit(0) msg = email.message_from_file( email_file ) if len( msg.as_string() ) < MSG_MAX_SIZE: ignore_email(msg) if not msg.is_multipart(): ignore_email(msg) parts = [] for part in msg.walk(): if len( part.as_string() ) > MSG_MAX_SIZE: part = strip_to_dir(part, MSG_DIR ) if part: parts.append(part) msg.set_payload(parts) print msg.as_string()