Skip to content

Instantly share code, notes, and snippets.

@Gerhut
Last active December 21, 2015 06:08
Show Gist options
  • Save Gerhut/6261669 to your computer and use it in GitHub Desktop.
Save Gerhut/6261669 to your computer and use it in GitHub Desktop.
Concaterate Mhtml Files
import sys
fout = open(sys.argv[0] + '.mht', 'w')
files = sorted(sys.argv[1:])
first = True
html_content = ''
attachment_contents = {}
for f in files:
data = open(f, 'r').read()
boundary_start = data.find('boundary="') + len('boundary="')
boundary_end = data.find('"', boundary_start)
boundary = '--' + data[boundary_start : boundary_end]
contents = data.split(boundary)[:-1]
html = contents[1].lower()
if first:
first = False
output_boundary = boundary
fout.write(contents[0])
fout.write(output_boundary)
else:
html = html[html.find('\n\n') + 2:]
html_content += html
for content in contents[2:]:
header = content[:content.find('\n\n')]
attachment_contents.setdefault(header, content)
fout.write(html_content)
fout.write(output_boundary)
for attachment_content in attachment_contents.itervalues():
fout.write(attachment_content)
fout.write(output_boundary)
fout.write('--\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment