Skip to content Skip to sidebar Skip to footer

Embed An Image In Html For Automatic Outlook365 Email Send

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 imp

Solution 1:

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']='swetjen@someplace.com'
msg['To']='swetjen@someplace.com'
msg['Subject']='My email with an embedded image.'

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

s.send_message(msg)

Post a Comment for "Embed An Image In Html For Automatic Outlook365 Email Send"