发送包含嵌入图像的多部分HTML邮件
我最近在玩Python的邮件模块,但我想知道怎么把图片嵌入到HTML中。
比如说,如果邮件的内容是这样的:
<img src="../path/image.png"></img>
我想把image.png这个图片嵌入到邮件里,并且要把src
属性换成content-id
。有没有人知道怎么做到这一点?
4 个回答
9
我意识到使用SMTP和邮件库时,有些事情真的很麻烦,所以我决定要做点什么。我制作了一个库,让在HTML中嵌入图片变得简单多了:
from redmail import EmailSender
email = EmailSender(host="<SMTP HOST>", port=0)
email.send(
sender="me@example.com",
receivers=["you@example.com"]
subject="An email with image",
html="""
<h1>Look at this:</h1>
{{ my_image }}
""",
body_images={
"my_image": "path/to/image.png"
}
)
抱歉有点宣传,但我觉得这个库真的很棒。你可以把图片作为Matplotlib的Figure
、Pillow的Image
,或者如果你的图片是这些格式的话,也可以直接用bytes
来提供。它使用Jinja来处理模板。
如果你需要控制图片的大小,也可以这样做:
email.send(
sender="me@example.com",
receivers=["you@example.com"]
subject="An email with image",
html="""
<h1>Look at this:</h1>
<img src="{{ my_image.src }}" width=200 height=300>
""",
body_images={
"my_image": "path/to/image.png"
}
)
你只需要用pip安装它就可以了:
pip install redmail
这(希望)就是你发送邮件所需的一切(还有更多功能),而且经过了充分的测试。我还写了详细的文档:https://red-mail.readthedocs.io/en/latest/,源代码可以在这里找到。
191
这里有一个我找到的例子。
食谱 473810:发送带嵌入图片的HTML邮件和纯文本备用:
HTML是一种很好的方式,适合那些想要发送包含丰富文本、布局和图形的邮件的人。通常,我们希望把图形直接嵌入到邮件中,这样收件人就可以直接查看邮件,而不需要再下载其他内容。
不过,有些邮件客户端不支持HTML,或者用户更喜欢接收纯文本邮件。因此,发送HTML邮件的人应该为这些用户提供一个纯文本的备用版本。
这个例子展示了如何发送一封简短的HTML邮件,里面包含一张嵌入的图片和一个备用的纯文本邮件。
# Send an HTML email with an embedded image and a plain text message for
# email clients that don't want to display the HTML.
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
# Define these once; use them twice!
strFrom = 'from@example.com'
strTo = 'to@example.com'
# Create the root message and fill in the from, to, and subject headers
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
msgRoot.preamble = 'This is a multi-part message in MIME format.'
# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)
# We reference the image in the IMG SRC attribute by the ID we give it below
msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>Nifty!', 'html')
msgAlternative.attach(msgText)
# This example assumes the image is in the current directory
fp = open('test.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
# Send the email (this example assumes SMTP authentication is required)
import smtplib
smtp = smtplib.SMTP()
smtp.connect('smtp.example.com')
smtp.login('exampleuser', 'examplepass')
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.quit()
93
适用于Python 3.4及以上版本。
之前的答案很好,但只适合旧版本的Python(2.x和3.3)。我觉得需要更新一下。
下面是如何在新版本的Python(3.4及以上)中实现这个功能:
from email.message import EmailMessage
from email.utils import make_msgid
import mimetypes
msg = EmailMessage()
# generic email headers
msg['Subject'] = 'Hello there'
msg['From'] = 'ABCD <abcd@xyz.com>'
msg['To'] = 'PQRS <pqrs@xyz.com>'
# set the plain text body
msg.set_content('This is a plain text body.')
# now create a Content-ID for the image
image_cid = make_msgid(domain='xyz.com')
# if `domain` argument isn't provided, it will
# use your computer's name
# set an alternative html body
msg.add_alternative("""\
<html>
<body>
<p>This is an HTML body.<br>
It also has an image.
</p>
<img src="cid:{image_cid}">
</body>
</html>
""".format(image_cid=image_cid[1:-1]), subtype='html')
# image_cid looks like <long.random.number@xyz.com>
# to use it as the img src, we don't need `<` or `>`
# so we use [1:-1] to strip them off
# now open the image and attach it to the email
with open('path/to/image.jpg', 'rb') as img:
# know the Content-Type of the image
maintype, subtype = mimetypes.guess_type(img.name)[0].split('/')
# attach it
msg.get_payload()[1].add_related(img.read(),
maintype=maintype,
subtype=subtype,
cid=image_cid)
# the message is ready now
# you can write it to a file
# or send it using smtplib