Python:SMTPLIB和MIMETEXT向电子邮件添加附件

时间:2014-10-29 12:14:19

标签: python email python-3.x gmail

iv刚开始使用python中的这些新模块,并且一直在学习如何发送电子邮件。我无法在网上找到解决方案......如何在此电子邮件脚本中添加图像/视频附件?

import smtplib
from email.mime.text import MIMEText

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 = MIMEText((msg_content+p1+p2), 'html')

message['From'] = 'Sender Name <sender>'
message['To'] = 'Receiver Name <receiver>'
message['Cc'] = 'Receiver2 Name <>'
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', 'receiver'],msg_full)
server.quit()

1 个答案:

答案 0 :(得分:0)

要包含附件,电子邮件的MIME类型应为multipart / mixed。您可以使用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:picture@example.com" 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', '<picture@example.com>')
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()