发送包含嵌入图片的多部分HTML电子邮件

102

我一直在尝试使用Python中的电子邮件模块,但我想知道如何嵌入包含在HTML中的图像。

比如说,如果邮件内容是这样的:

<img src="../path/image.png"></img>

我想在电子邮件中嵌入image.png,并将src属性替换为content-id。 有人知道如何做到这一点吗?

5个回答

189

这里有一个我找到的例子。

食谱 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()

非常感谢,我尝试了许多解决方案,这个是完美运作的! - wukong
我针对第二个msgText实例添加了msgText.replace_header('Content-Type','text/html')。 - Old Geezer
3
Ftr: MIMEText 构造函数 的第二个参数是子类型(默认为 plain,第二个实例是 'html')。 - dtk
我尝试了相同的代码来发送多个嵌入式图像,但是第一个图像被嵌入,而其余的则没有被嵌入,我们如何嵌入多个图像? - Shoban Sundar
15
在Python 3.7.2中,这对我起作用了,但我必须以不同的方式编写导入语句:`from email.mime.text import MIMEText` `from email.mime.image import MIMEImage` `from email.mime.multipart import MIMEMultipart` - senya
显示剩余6条评论

92

适用于 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

3
email.examples 中有一个非常相似的示例(从底部数第二个)。 - gregV
有没有办法使用 msg = MIMEMultipart() 来重现这个问题? - MrChadMWood
2
@MrChadMWood 的 .add_alternative() 方法会自动将其转换为 MIMEMultipart('alternative') - undefined

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/,源代码可以在这里找到。


0

事实上,这里有一个非常好的帖子,提供了多种解决此问题的方法这里。因为它,我能够发送包含HTML、Excel附件和嵌入式图像的电子邮件。


-5

代码运行正常

    att = MIMEImage(imgData)
    att.add_header('Content-ID', f'<image{i}.{imgType}>')
    att.add_header('X-Attachment-Id', f'image{i}.{imgType}')
    att['Content-Disposition'] = f'inline; filename=image{i}.{imgType}'
    msg.attach(att)

2
嗨!感谢分享答案。如果您能对上面的代码进行一些解释,那将非常有用。此外,在 OP 的代码中,我没有看到 imgType 变量的定义,因此您的代码将引发异常。 - Charnel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接