Python - 发送带多个图像附件的电子邮件

4
我正在尝试使用Python发送带有多个图像附件的电子邮件。然而,使用下面的代码,我只能在正文中包含第一个图像,而第二个图像则作为附件附加到电子邮件中。是否有办法让两个图像都出现在HTML正文中?以下是我的当前代码。
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

strFrom = 'user@provider.com'
strTo = 'user@provider.com'

msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'Test message'
msgRoot['From'] = 'user@provider.com'
msgRoot['To'] = 'user@provider.com'
msgRoot.preamble = 'This is a multi-part message in MIME format.'

msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)

msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)

msgText = MIMEText('<b>Test HTML with Images</b><br><br>'
                   '<img src="cid:image1">'
                   '<br>'
                   '<br>'
                   '<img src="cid:image2">'
                   '<br>'
                   '<br>'
                   'Sending Two Attachments', 'html')

msgAlternative.attach(msgText)

fp = open('image1.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

fp = open('image2.png', 'rb')
msgImage2 = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image2>')
msgRoot.attach(msgImage2)

import smtplib
smtp = smtplib.SMTP('localhost')
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.quit()

我不是很确定,但代码看起来还好。我找到了这篇关于在Python中发送多个内联图片的文章,希望能有所帮助。 - ionescu77
2个回答

3
我认为代码应该是:

我认为代码应该是:

fp = open('image1.png', 'rb')
msgImage1 = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage1)

fp = open('image2.png', 'rb')
msgImage2 = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image2>')
msgRoot.attach(msgImage2)

您需要明确指定是image1而不仅仅是image


没错,这就是我的意思。我当时在工作,无法很好地编辑它。谢谢你,巴里! - Xiong Chu
示例代码几乎正确,'add_header' 行需要分别引用 msgImage1 和 msgImage2。 - captcha

1

您是否尝试将MIMEMultipart更改为mixed。我有代码可以包含图像,并且对于我而言,混合模式运作良好。

msgRoot = MIMEMultipart('mixed')
msgAlternative = MIMEMultipart('mixed')

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