2
# largely taken from python examples
3
# http://docs.python.org/library/email-examples.html
8
# For guessing MIME type based on file name extension
11
from email import encoders
12
from email.message import Message
13
from email.mime.base import MIMEBase
14
from email.mime.multipart import MIMEMultipart
15
from email.mime.text import MIMEText
16
from optparse import OptionParser
21
starts_with_mappings = {
22
'#include': 'text/x-include-url',
23
'#!': 'text/x-shellscript',
24
'#cloud-config': 'text/cloud-config',
25
'#cloud-config-archive': 'text/cloud-config-archive',
26
'#upstart-job': 'text/upstart-job',
27
'#part-handler': 'text/part-handler',
28
'#cloud-boothook': 'text/cloud-boothook'
32
def get_type(fname, deftype):
38
# slist is sorted longest first
39
slist = sorted(starts_with_mappings.keys(), key=lambda e: 0 - len(e))
41
if line.startswith(sstr):
42
rtype = starts_with_mappings[sstr]
48
outer = MIMEMultipart()
49
#outer['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
50
#outer['To'] = COMMASPACE.join(opts.recipients)
51
#outer['From'] = opts.sender
52
#outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
54
parser = OptionParser()
56
parser.add_option("-o", "--output", dest="output",
57
help="write output to FILE [default %default]", metavar="FILE",
59
parser.add_option("-z", "--gzip", dest="compress", action="store_true",
60
help="compress output", default=False)
61
parser.add_option("-d", "--default", dest="deftype",
62
help="default mime type [default %default]", default="text/plain")
63
parser.add_option("--delim", dest="delim",
64
help="delimiter [default %default]", default=":")
66
(options, args) = parser.parse_args()
69
parser.error("Must give file list see '--help'")
72
t = arg.split(options.delim, 1)
77
mtype = get_type(path, options.deftype)
79
maintype, subtype = mtype.split('/', 1)
80
if maintype == 'text':
82
# Note: we should handle calculating the charset
83
msg = MIMEText(fp.read(), _subtype=subtype)
87
msg = MIMEBase(maintype, subtype)
88
msg.set_payload(fp.read())
90
# Encode the payload using Base64
91
encoders.encode_base64(msg)
93
# Set the filename parameter
94
msg.add_header('Content-Disposition', 'attachment',
95
filename=os.path.basename(path))
99
if options.output is "-":
102
ofile = file(options.output, "wb")
105
gfile = gzip.GzipFile(fileobj=ofile, filename=options.output)
106
gfile.write(outer.as_string())
109
ofile.write(outer.as_string())
113
if __name__ == '__main__':