1

I am using Python 2.7 and trying to send an email using smtplib/MIMEMultipart. I want to send an email that contains multiple pieces e.g., a text message and an html message. I do NOT want them to be alternatives. I want to it to display the text message (inline) follow by the html (inline)

In the future, I would also like to include images. So, the message will contain text, html, and images all inline.

Here is what I have currently, which produces a text message and then the html as an attachment

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib

s = smtplib.SMTP('localhost')

#this part works
msg = MIMEMultipart('mixed')
msg['Subject'] = subject
msg['From'] = from
msg['To'] = to

html_str = """<html><head></head><body><p>Test</p></body></html>"""

#this shows up with "This is my text" inline and the html as an attachment
text = MIMEText("This is my text", 'plain')
html = MIMEText(html_str, 'html')

msg.attach(text)
msg.attach(html)

s.sendmail(fromEmail, toEmail, msg.as_string())
s.quit()

How do I add multiple inline pieces to an email? Thank you for your help

  • Welcome to Stack Overflow. SO is a question-and-answer site, but you have not included a question in your post. What is your specific question? – Robᵩ Aug 05 '13 at 14:51
  • Also, you might be interested in the [Content-Disposition:](http://en.wikipedia.org/wiki/MIME#Content-Disposition) header. – Robᵩ Aug 05 '13 at 14:57
  • Thanks Rob. I have updated my question. I am unsure of how to add multiple parts to an email in a way that they all appear inline (and not as attachments). – cameron.wyatt Aug 05 '13 at 15:20
  • Check out this answer: http://stackoverflow.com/questions/3362600/how-to-send-email-attachments-with-python It provides an example of how to attach additional attachments. If you want to go easy mode check out http://ginstrom.com/code/mailer.html where adding attachments is just passing an array of filenames as part of the object creation. Nifty. – synthesizerpatel Aug 05 '13 at 20:52
  • Synthesizerpatel, thank you for the response, but that answer is in regards to multiple attachments. I am looking for multiple **inline** pieces (they should not be attachments) – cameron.wyatt Aug 06 '13 at 12:39

1 Answers1

1

I wasn't able to do this exactly as I wanted, but I found a work around.

I ended up just making the entire email an html email. For every piece that I needed to add, I would just add html code. For example, here is how I ended up adding an image

html_list.append('<img src="cid:image.png">')
img = MIMEImage(my_data)
img.add_header('Content-ID', '<image.png>')
msg.attach(img)

And if I wanted to add text, I could add it as a header (e.g. <h3>My Text</h3>) or as any other html element.