2017-09-28 57 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') 
相關問題