2
# largely taken from python examples
3
# http://docs.python.org/library/email-examples.html
8
from email import encoders
9
from email.mime.base import MIMEBase
10
from email.mime.multipart import MIMEMultipart
11
from email.mime.text import MIMEText
12
from optparse import OptionParser
17
starts_with_mappings = {
18
'#include': 'text/x-include-url',
19
'#include-once': 'text/x-include-once-url',
20
'#!': 'text/x-shellscript',
21
'#cloud-config': 'text/cloud-config',
22
'#cloud-config-archive': 'text/cloud-config-archive',
23
'#upstart-job': 'text/upstart-job',
24
'#part-handler': 'text/part-handler',
25
'#cloud-boothook': 'text/cloud-boothook'
31
return (True, data.decode())
32
except UnicodeDecodeError:
36
def get_type(fname, deftype):
39
with open(fname, "rb") as f:
40
(can_be_decoded, line) = try_decode(f.readline())
43
# slist is sorted longest first
44
slist = sorted(list(starts_with_mappings.keys()),
45
key=lambda e: 0 - len(e))
47
if line.startswith(sstr):
48
rtype = starts_with_mappings[sstr]
51
rtype = 'application/octet-stream'
57
outer = MIMEMultipart()
58
parser = OptionParser()
60
parser.add_option("-o", "--output", dest="output",
61
help="write output to FILE [default %default]",
62
metavar="FILE", default="-")
63
parser.add_option("-z", "--gzip", dest="compress", action="store_true",
64
help="compress output", default=False)
65
parser.add_option("-d", "--default", dest="deftype",
66
help="default mime type [default %default]",
68
parser.add_option("--delim", dest="delim",
69
help="delimiter [default %default]", default=":")
71
(options, args) = parser.parse_args()
74
parser.error("Must give file list see '--help'")
77
t = arg.split(options.delim, 1)
82
mtype = get_type(path, options.deftype)
84
maintype, subtype = mtype.split('/', 1)
85
if maintype == 'text':
87
# Note: we should handle calculating the charset
88
msg = MIMEText(fp.read(), _subtype=subtype)
92
msg = MIMEBase(maintype, subtype)
93
msg.set_payload(fp.read())
95
# Encode the payload using Base64
96
encoders.encode_base64(msg)
98
# Set the filename parameter
99
msg.add_header('Content-Disposition', 'attachment',
100
filename=os.path.basename(path))
104
if options.output is "-":
105
if hasattr(sys.stdout, "buffer"):
106
# We want to write bytes not strings
107
ofile = sys.stdout.buffer
111
ofile = open(options.output, "wb")
114
gfile = gzip.GzipFile(fileobj=ofile, filename=options.output)
115
gfile.write(outer.as_string().encode())
118
ofile.write(outer.as_string().encode())
122
if __name__ == '__main__':