【问题标题】:Embed an image in html for automatic outlook365 email send在 html 中嵌入图像以自动发送 Outlook365 电子邮件
【发布时间】:2018-06-24 14:55:18
【问题描述】:

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

这是html中的sn-p

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

这是我在实际发送的电子邮件中看到的

我觉得我在做一些对大多数人来说可能很明显的错误。

【问题讨论】:

标签: python email outlook smtp


【解决方案1】:

根据您的 HTML sn-p,我将尝试一下。

您的 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)

【讨论】:

    猜你喜欢
    • 2011-10-06
    • 2015-03-14
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    相关资源
    最近更新 更多