git » sea » master » tree

[master] / sea

#!/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 email.utils
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

	date = time.localtime()
	if 'date' in m:
		date = email.utils.parsedate(m['date'])

	# put the attachments in basepath/<time>-<from>
	outpath = "%s/%s~%s/" % (basepath,
			time.strftime("%Y-%m-%d-%H:%M:%S", date),
			f_email.replace('/', ''),)

	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

		# do this here, once we know there is something to put in the
		# directory
		if not os.path.exists(outpath):
			os.mkdir(outpath)

		fname = part.get_filename('')
		# "=?" tells us that the name is broken (an attempt to encode
		# it that went wrong), so just assign a name ourselves
		if not fname or "=?" in fname:
			ext = mimetypes.guess_extension(
					part.get_content_type() )
			if ext:
				fname = 'att-%d%s' % (count, ext)
			else:
				fname = 'att-%d' % count
		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]))