python - 如何通过Python 3.5将base64图像嵌入到HTML电子邮件中?

标签 python html-email mime

我正在构建一封嵌入图像 base64 的电子邮件,这样当我的同事打开它时它可以正确显示。我不太确定如何从文件中到达那里以及我现在拥有的内容。

这运行得很好,但我无法成功嵌入图像。我需要嵌入 image1.jpg。

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage


# me == my email address
# you == recipient's email address
me = "me@.com"
you = "you@.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Sent using Python :) "
msg['From'] = me
msg['To'] = you



# Create the body of the message (a plain-text and an HTML version).
text = "This is an HTML body. I would like to embed a base64 image."
html = """\
<html>
    <body>
        <p>This is an HTML body.<br>
           I would like to embed a base64 image.
        </p>
    </body>
</html>
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')


# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()

最佳答案

我仅使用嵌入 HTML 文件中的 Base64 图像进行了测试,但它应该是相同的。

<小时/>

您必须将图像读取为字节,编码为base64,将其转换为字符串,然后在

中使用
  '<img src="data:image/jpeg;base64,' + data_base64 + '">'

在 HTML 文件中嵌入 Base64 图像的工作示例:

import base64

data = open('image.jpg', 'rb').read() # read bytes from file
data_base64 = base64.b64encode(data)  # encode to base64 (bytes)
data_base64 = data_base64.decode()    # convert bytes to string

print(data_base64)

#html = '<html><body><img src="data:image/jpeg;base64,' + data_base64 + '"></body></html>' # embed in html
html = '<img src="data:image/jpeg;base64,' + data_base64 + '">' # embed in html
open('output.html', 'w').write(html)
<小时/>

示例 encode and decode base64 image

关于python - 如何通过Python 3.5将base64图像嵌入到HTML电子邮件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57829797/

相关文章:

python - keras中的fit_generator,将所有内容加载到内存中

python - 如何让 .py 文件直接打开到 Idle

php - Woocommerce 电子邮件表格自定义

html - 如何将响应式电子邮件的图像右对齐,左侧留有空白

javascript - 如何添加base64编码图像的路径

php - MIME 类型检查对文件上传没用? (特别是使用 Javascript 文件 API)?

linux - mac 和 linux 中的 mime 插件文件的位置在哪里?

python - Flask 应用程序无法在浏览器中加载

python - 在 numpy 中创建 "white"图像(二维图像)

jakarta-mail - MimeMessage 电子邮件获取没有先前信件的回复正文