在MIME中嵌入图像内嵌

时间:2018-01-26 22:44:55

标签: python email mime

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

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)

1 个答案:

答案 0 :(得分:0)

从上面给出的评论中,答案如下。

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

# 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)