Python - Send email with multiple image attachments

Viewed 5194

I'm trying to send an email using Python with multiple image attachments. However with the code below I am able to include the first image in the body of the text but the second image gets attached to the email as an attachment. Is there a way I can get both images in the body of the HTML? Below is my current code.

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

strFrom = 'user@provider.com'
strTo = 'user@provider.com'

msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'Test message'
msgRoot['From'] = 'user@provider.com'
msgRoot['To'] = 'user@provider.com'
msgRoot.preamble = 'This is a multi-part message in MIME format.'

msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)

msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)

msgText = MIMEText('<b>Test HTML with Images</b><br><br>'
                   '<img src="cid:image1">'
                   '<br>'
                   '<br>'
                   '<img src="cid:image2">'
                   '<br>'
                   '<br>'
                   'Sending Two Attachments', 'html')

msgAlternative.attach(msgText)

fp = open('image1.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

fp = open('image2.png', 'rb')
msgImage2 = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image2>')
msgRoot.attach(msgImage2)

import smtplib
smtp = smtplib.SMTP('localhost')
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.quit()
2 Answers

I think the code should be:

fp = open('image1.png', 'rb')
msgImage1 = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage1)

fp = open('image2.png', 'rb')
msgImage2 = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image2>')
msgRoot.attach(msgImage2)

You need to specify it's image1 instead of just image

Have you tried to change MIMEMultipart to mixed. I have code to include images and use mixed mode works well for me.

msgRoot = MIMEMultipart('mixed')
msgAlternative = MIMEMultipart('mixed')
Related