【发布时间】:2018-03-09 16:54:27
【问题描述】:
我正在尝试使用带有多个图像附件的 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()
【问题讨论】:
-
我不太确定,代码似乎还可以。我找到了这个article about emailing multiple inline images in python,希望对您有所帮助。