【问题标题】:How to embed a base64 image into HTML email via Python 3.5?如何通过 Python 3.5 将 base64 图像嵌入 HTML 电子邮件?
【发布时间】:2020-01-09 18:59:33
【问题描述】:

我正在尝试构建一个嵌入图像 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()

【问题讨论】:

    标签: python html-email mime


    【解决方案1】:

    我仅使用嵌入在 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

    【讨论】:

      猜你喜欢
      • 2014-03-09
      • 1970-01-01
      • 2018-06-29
      • 2012-03-30
      • 1970-01-01
      • 2010-12-23
      • 2014-02-16
      • 2014-01-25
      • 1970-01-01
      相关资源
      最近更新 更多