notbad.jpeg
notbad.jpeg

Reputation: 3368

Python Emailing Multipart with body content

I can't send an e-mail in python with a body as a multipart email. Everything I've tried has resulted in all of the content as attachments, and I can't get the text or html to show up in the body.

msg = MIMEMultipart()
if msg_mime_type == 'text' or not msg_mime_type:
    new_body = MIMEText(body, 'text')
elif msg_mime_type == 'image':
    new_body = MIMEImage(body)
elif msg_mime_type == 'html':
    new_body = MIMEText(body, 'html')
new_body.add_header('Content-Disposition', 'inline', filename='body')
msg.set_payload(new_body) #also tried msg.attach(new_body)

I need to use a Multipart so that i can also add attachments, but I kept that code out for simplicity.

Upvotes: 2

Views: 6592

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122342

You need to specify that the parts are alternatives of one another, e.g. the multipart/alternative mime type:

msg = MIMEMultipart('alternative')

The default is mixed; see the email library examples.

Note that to create an email with both attachments and an alternative (HTML / CSS) option you'll need to have a top-level multipart/related container that contains the alternative parts as the first entry.

Upvotes: 5

Related Questions