2

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.

notbad.jpeg
  • 3,308
  • 1
  • 32
  • 37

1 Answers1

5

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • now yahoo registered no body or attachments, gmail registered it as an attachment – notbad.jpeg Aug 16 '12 at 21:34
  • @notbad.jpeg: you'll need to nest mime parts; the main message is multipart/alternative (reader can pick either HTML or Text) but the rest of the messages need to be part of your email but not part of the alternatives. – Martijn Pieters Aug 16 '12 at 21:36
  • yeah this hasn't helped me at all, it actually confused me more, maybe you could post a larger code snippet? – notbad.jpeg Aug 16 '12 at 22:35
  • Example `alternative` multipart message building here on SO: [Python: Sending Multipart html emails which contain embedded images](http://stackoverflow.com/q/920910) – Martijn Pieters Aug 16 '12 at 22:40
  • Example on the Python Recipes site: http://code.activestate.com/recipes/576931-send-a-multipart-email/ – Martijn Pieters Aug 16 '12 at 22:42