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

Python - Send email with multiple image attachments

我正在尝试使用 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()

您是否尝试过将 MIMEMultipart 更改为 mixed。我有包含图像和使用混合模式的代码对我来说效果很好。

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

我认为代码应该是:

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