【问题标题】:Embedding images inline in MIME在 MIME 中嵌入图像
【发布时间】:2018-07-06 08:10:51
【问题描述】:

我正在尝试在电子邮件中嵌入图像。问题是,当我发送电子邮件时,图像显示为附件而不是内联。我该如何解决这个问题?

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

COMMASPACE = ', ' 

# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
me = "sender@email.com"
family = ["recipient1@email.com", "recipient2@email.com"]
msg['From'] = me
msg['To'] = COMMASPACE.join(family)
msg.preamble = 'Preamble'

html = """\
<h1>Read this email header!</h1>
"""

# image
logo = "image1.png"
fp = open(logo, 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)

# body text
text = "<i>Read this text!</i>"
bodytext = MIMEText(text, 'html')
msg.attach(bodytext)

【问题讨论】:

标签: python email mime


【解决方案1】:

从上面给出的cmets,答案如下。

为图像添加标题(此代码块中的倒数第二行):

# image
logo = "image1.png"
fp = open(logo, 'rb')
img = MIMEImage(fp.read())
fp.close()
img.add_header('Content-ID', 'image')
msg.attach(img)

对于文本,添加一个带有属性src 的图像标签,该标签与您修改的内容相对应。请注意,cid 是 Content-ID 的缩写。

# body text
text = "<img src="cid:image"><i>Read this text!</i>"
bodytext = MIMEText(text, 'html')
msg.attach(bodytext)

【讨论】:

    猜你喜欢
    • 2017-11-05
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 2015-03-28
    相关资源
    最近更新 更多