Embed an image in html for automatic outlook365 email send

Deadly 提交于 2020-02-05 07:38:06

问题


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

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


回答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)


来源:https://stackoverflow.com/questions/48272100/embed-an-image-in-html-for-automatic-outlook365-email-send

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!