在html中嵌入图像以进行自动outlook365电子邮件发送

时间:2018-01-15 23:26:41

标签: python email outlook smtp

我正在尝试使用smtp和python中的电子邮件在我的html代码中嵌入和映像。 包裹是: 导入smtplib 来自email.mime.multipart导入MIMEMultipart 来自email.mime.text导入MIMEText

这是html

中的代码段
<img border=0 width=231 height=67 src="Hello_files/image001.png">

这是我在实际发送的电子邮件中看到的内容 enter image description here

我觉得我做的事情非常错误,这对大多数人来说可能是显而易见的。

1 个答案:

答案 0 :(得分:0)

根据您的HTML代码段,我将采取行动。

您的HTML

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

您正在引用本地文件系统中显示的图像,但在收件人计算机中的电子邮件上下文中,该目录和文件名将不存在。

示例HTML

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

这里我们将图像引用为 cid:image1 。在我们的python代码中,我们加载图像并对其进行编码以匹配我们的html。在下面的示例中,图像 test.png 与我们的python脚本位于同一目录中。

MIME图像编码示例

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)
相关问题