2017-09-28 61 views
1

我试图使用Python发送带有多个图像附件的电子邮件。但是,通过下面的代码,我可以在文本正文中包含第一张图片,但第二张图片会作为附件附加到电子邮件中。有没有一种方法可以在HTML的主体中获得这两个图像?以下是我目前的代码。Python - 发送带有多个图像附件的电子邮件

from email.mime.multipart import MIMEMultipart 
from email.mime.text import MIMEText 
from email.mime.image import MIMEImage 

strFrom = '[email protected]' 
strTo = '[email protected]' 

msgRoot = MIMEMultipart('related') 
msgRoot['Subject'] = 'Test message' 
msgRoot['From'] = '[email protected]' 
msgRoot['To'] = '[email protected]' 
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() 
+0

我不太确定,代码看起来没问题。我发现这篇文章[关于通过电子邮件发送多个嵌入式图像](http://dogdogfish.com/python-2/emailing-multiple-inline-images-in-python/),希望它有帮助。 – ionescu77

回答

0

您是否尝试将MIMEMultipart更改为mixed。我有代码包含图像,并使用混合模式适合我。

msgRoot = MIMEMultipart('mixed') 
msgAlternative = MIMEMultipart('mixed') 
相关问题