0

It seems like there should be a better way to do this. I have a plain text email, and I'd like to convert it to a multipart email. I can do it like this:

import commonmark

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.parser import BytesParser

raw_msg = b'''
To: you@example.com
From: me@example.com
Subject: This is a sample

# This should be h1

Something

## This should be h2

Email from markdown? Sweet
'''.strip()


msg = BytesParser().parsebytes(raw_msg)
html = commonmark.commonmark(msg.get_payload())
new_msg = MIMEMultipart()
for key in msg.keys():
    new_msg[key] = msg.get(key)

new_msg.attach(MIMEText(msg.get_payload()))
new_msg.attach(MIMEText(html, 'html'))

print(str(new_msg))

Which appears to work, but it also seems clunky to me. Is there a way in Python to just create a multipart email from my original message? Or am I doing it the right way?

Wayne Werner
  • 49,299
  • 29
  • 200
  • 290

1 Answers1

0

If your input is a single-part email message then yeah, parsing it and extracting the payload is probably the way to go.

Having the parser "convert" the message to multipart on the fly doesn't seem feasible, or particularly well-defined. Be happy that the input is simple.

The outer container for your new message should probably be explicitly multipart/alternative; the default type multipart/mixed does not convey the semantics of variant encodings of the same message which you seem to be striving for.

Notice that the email library was officially overhauled in Python 3.5. You might want to explore transitioning your code to use the newer EmailMessage class hierarchy instead, though I don't believe it will bring any immediate benefits for this particular use case. Overall, the new code base is more versatile and disciplined than the old somewhat ad-hoc legacy email library (now known as compat32, as in Python 3.2; the overhaul was unofficially introduced already in Python 3.3).

tripleee
  • 175,061
  • 34
  • 275
  • 318