1
votes

I am trying to embed and image in my html code using smtp and email in python. Packages are: import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText

This is the snippet in the html

<img border=0 width=231 height=67 src="Hello_files/image001.png">

This is what I see in the actual email send enter image description here

I feel like I am doing something very wrong that is probably obvious to most.

1
Nope not a duplicate. They are getting two I am getting nonemegv
Can you post the code you're using with smtplib? @megvSpence Wetjen

1 Answers

1
votes

Based on your HTML snippet I'll take a swing at this.

Your HTML

<img border=0 width=231 height=67 src="Hello_files/image001.png">

You're referencing the image as it appears in your local filesystem but in the context of the email in a recipient's computer, that directory and file name won't exist.

Example HTML

<img src='cid:image1' alt='image' style="display: block;margin: auto;width: 100%;">

Here we reference the image as cid:image1. In our python code, we load the image and encode it to match up with our html. In the example below, the image test.png is in the same directory as our python script.

Example MIME Image Encoding

s = smtplib.SMTP(host='smtp.gmail.com', port=587)
s.starttls()
s.login('email','password')

msg = MIMEMultipart()  # create a message

email_body = "<img src='cid:image1' alt='image' style="display: block;margin: auto;width: 100%;">"

# Read and encode the image
img_data = open('./test.png', 'rb').read()
image = MIMEImage(img_data)
image.add_header('Content-ID', '<image1>')
msg.attach(image)

# Construct the email
msg['From']='[email protected]'
msg['To']='[email protected]'
msg['Subject']='My email with an embedded image.'

msg.attach(MIMEText(email_body, _subtype='html'))

s.send_message(msg)