def make_multipart(msg): '''Takes a flat message and turns it into a message with a single text/plain attachment.''' plaintext = msg.get_payload() msg.set_payload(None) msg.set_type('multipart/alternative') plainpart = MIMEText(plaintext, 'plain') plainpart.del_param('name') msg.attach(plainpart)
def process_message(origmsg, flags=None): global opts msg = copy.deepcopy(origmsg) if flags is None: flags = set() if not msg.is_multipart(): if msg.get_content_type() != 'text/plain': # We don't know what to do with this message. raise InvalidInputMessage('Main body is not text/plain') make_multipart(msg) # Make sure there is only one text/plain part and that it is # the first part. if msg.get_payload()[0].get_content_type() != 'text/plain': raise InvalidInputMessage('first part is not text/plain') found_text_part = False for p in msg.get_payload(): if p.get_content_type() == 'text/plain': if found_text_part: raise InvalidInputMessage('More than one text/plain part') found_text_part = True plainpart = msg.get_payload()[0] auxparts = msg.get_payload()[1:] rootpart = MIMEMultipart('related') msg.set_payload(None) msg.set_type('multipart/alternative') plaintext = plainpart.get_payload() msgflags, plaintext, content, signature = get_markdown_content(plaintext) if msgflags is None and not opts.always: raise InvalidInputMessage('No markdown marker.') elif msgflags is not None: flags.update(msgflags) # Append the signature as a `<pre>` block to the markdown # content. if signature not 'strip-signature' in flags: content = content + '\n<pre>-- \n%s\n</pre>' % signature # render the markdown content to HTML htmltext = markdown.markdown(content, extras=[ 'footnotes', 'wiki-tables', 'code-friendly']) htmlpart = MIMEText(htmltext, 'html') htmlpart.del_param('name') if not 'only-html' in flags: plainpart = MIMEText(plaintext) msg.attach(plainpart) if 'include-src' in flags: mdpart = MIMEText(content, 'x-markdown') msg.attach(mdpart) rootpart.attach(htmlpart) for part in auxparts: if part.get_filename(): part.add_header('Content-ID', '<%s>' % part.get_filename()) rootpart.attach(part) msg.attach(rootpart) return msg