Skip to content
Advertisement

Embedding image in HTML email using Python

I have been trying to embed images to an email using MIMEImage but even after replicating examples I find online, I keep having the same issue…

Here is the part of the HTML that embeds the image:

<img width=779 height=467 style='width:8.1145in;height:4.8645in' src="cid:image001" alt="HRX Trend"> 

This is my Python code:

msg = MIMEMultipart('alternative')
msg['Subject'] = "test for daily email"
msg['From'] = me
msg['To'] = you

fp = open('path\name.jpeg', 'rb')
msgImage = MIMEImage(fp.read())

msgImage.add_header('Content-ID', '<image001>')

part2 = MIMEText(html, 'html')

msg.attach(part2)
msg.attach(msgImage)

s = smtplib.SMTP('domain', port)
s.sendmail(me, you, msg.as_string())
s.quit()

But, when the email sends, I keep getting the error saying: The linked image cannot be displayed. The file may have been moved, renamed, or deleted.

Screenshot of what the email ends up looking like:

Screenshot of what the email ends up looking like

I have no idea what I am doing wrong…

Thank you!

Advertisement

Answer

I updated the message container and the issue was resolved:

Original:

msg = MIMEMultipart('alternative')
msg['Subject'] = "test for daily email"
msg['From'] = me
msg['To'] = you

New:

msg = MIMEMultipart()
msg['Subject'] = "test for daily email"
msg['From'] = me
msg['To'] = you
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement