Skip to content

Instantly share code, notes, and snippets.

@noah
Created February 7, 2010 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noah/297363 to your computer and use it in GitHub Desktop.
Save noah/297363 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import os
import sys
import datetime
import email
import mimetypes
# attachment root directory
AD = "/backup/ns_cache/"
# message object
msg = email.message_from_file(sys.stdin)
# Put the attachment into a bucket, based
# upon the subject of the email. Commas
# in the subject are treated as delimiters,
# allowing for nesting.
id = '/'.join(msg['subject'].split('.'))
bucket = os.path.join(AD,id)
if not os.path.exists(bucket):
print "Creating %(id)s" % locals()
os.makedirs(bucket,0755)
else:
print "%(id)s exists" % locals()
try:
# save attachments to the bucket
c = 1
for part in msg.walk():
if part.get_content_maintype() == 'multipart':
continue
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")
filename = part.get_filename()
if not filename:
ext = mimetypes.guess_extension(part.get_content_type())
if not ext:
ext = '.bin'
filename = 'part-%03d%s' % (c,ext)
name,ext = filename.split('.')
filename = '.'.join(['_'.join([name,timestamp]),ext])
c += 1
out_path = os.path.join(bucket,filename)
print "Writing %(out_path)s" % locals()
fp = open(out_path,'wb')
fp.write(part.get_payload(decode=True))
fp.close()
except Exception as e:
print "Error: %(e)s" % locals()
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment