要包含附件,電子郵件消息應該具有multipart/mixed的MIME類型。您可以使用email.mime.multipart.MIMEMultipart
創建多部分消息。
您可以發送圖片附件,像這樣:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
message = MIMEMultipart()
abc = 'BLACK TITLE'
msg_content = '<h2>{title} <font color="green">TITLE HERE</font></h2>'.format(title=abc)
p1 = '<p>new line (paragraph 1)<\p>'
p2 = '<p>Image below soon hopefully...<\p>'
message.attach(MIMEText((msg_content+p1+p2), 'html'))
with open('image.jpg', 'rb') as image_file:
message.attach(MIMEImage(image_file.read()))
message['From'] = sender
message['To'] = receiver
message['Subject'] = 'Python Test E-mail'
msg_full = message.as_string()
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(sender, password)
server.sendmail(sender,[receiver],msg_full)
server.quit()
如果你想在你的HTML中使用的圖片,他們需要有一個Content-ID
標題:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
message = MIMEMultipart('related')
msg_content = '''
<html><body><p><table><tr>
<td>Hello,</td>
<td><img src="cid:[email protected]" width="150" height="150"></td>
<td>world</td>
</tr></table></p></body></html>'''
message.attach(MIMEText((msg_content), 'html'))
with open('image.jpg', 'rb') as image_file:
image = MIMEImage(image_file.read())
image.add_header('Content-ID', '<[email protected]>')
image.add_header('Content-Disposition', 'inline', filename='image.jpg')
message.attach(image)
message['From'] = sender
message['To'] = receiver
message['Subject'] = 'Python Test E-mail'
msg_full = message.as_string()
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(sender, password)
server.sendmail(sender,[receiver],msg_full)
server.quit()
你的回答被發現[在文檔中](https://docs.python.org/2/library/email-examples.html)。 – 2014-10-29 13:48:26