python-发送带图片的邮件

实现步骤

  • 设置邮件为多文本格式

    1
    MIMEMultipart('related')
    • 编写html格式内容包含图片信息

      1
      2
      msgHtmlImg = '<img src="cid:image{count}"><br>'
      MIMEText(msgHtmlImg, 'html')
    • 读取图片并添加邮件头

      1
      2
      3
      4
      5
      6
      7
      fp = open(imgpath, 'rb')
      msgImage = MIMEImage(fp.read())
      fp.close()
      # Define the image's ID as referenced above
      msgImage.add_header('Content-ID', '<image{count}>'.format(count=i))
      msgRoot.attach(msgImage)

完整发送邮件lib源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import smtplib
import os
import logging
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
logger = logging.getLogger("django")
class EmailHandler(object):
def __init__(self, smtpserver, user, pwd):
self.smtp = smtplib.SMTP()
self.smtpserver = smtpserver
self.smtpuser = user
self.smtppwd = pwd
def generateAlternativeEmailMsgRoot(self, strFrom, listTo, listCc, strSubJect, strMsgText, strMsgHtml, listImagePath):
# Create the root message and fill in the from, to, and subject headers
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = strSubJect
msgRoot['From'] = strFrom
msgRoot['To'] = ",".join(listTo)
if listCc:
msgRoot['Cc'] = ",".join(listCc)
msgRoot.preamble = 'This is a multi-part message in MIME format.'
# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgContent = strMsgText.replace("\n","<br>") if strMsgText else ""
msgContent += "<br>" + strMsgHtml if strMsgHtml else ""
# We reference the image in the IMG SRC attribute by the ID we give it below
if listImagePath and len(listImagePath)>0:
msgHtmlImg = msgContent + "<br>"
for imgcount in range(0, len(listImagePath)):
msgHtmlImg += '<img src="cid:image{count}"><br>'.format(count=imgcount)
msgText = MIMEText(msgHtmlImg, 'html')
msgAlternative.attach(msgText)
# print(msgHtmlImg)
# This example assumes the image is in the current directory
for i,imgpath in enumerate(listImagePath):
fp = open(imgpath, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<image{count}>'.format(count=i))
msgRoot.attach(msgImage)
else:
msgText = MIMEText(msgContent, 'html')
msgAlternative.attach(msgText)
return msgRoot
# Send the email (this example assumes SMTP authentication is required)
def sendemail(self, strFrom, listTo, strSubJect, strMsgText, strMsgHtml=None, listImagePath=None, listCc=None):
msgRoot = self.generateAlternativeEmailMsgRoot(strFrom, listTo, listCc, strSubJect, strMsgText, strMsgHtml, listImagePath)
try:
self.smtp = smtplib.SMTP()
self.smtp.connect(self.smtpserver)
self.smtp.login(self.smtpuser, self.smtppwd)
if listCc:
listTo = listTo + listCc
self.smtp.sendmail(strFrom, listTo, msgRoot.as_string())
self.smtp.quit()
logger.info("Send mail success {0}".format(strSubJect))
except Exception as e:
logger.error("ERROR:Send mail failed {0} with {1}".format(strSubJect, str(e)))
# if __name__ == "__main__":
# smtpserver = 'smtp.exmail.qq.com'
# smtpport = 465
# username = 'autotest.com'
# password = '123456'
# strFrom = 'autotest@autotest.com'
# strTo = ['autotest@autotest.com','autotest@autotest.com']
# strCc = ['autotest@autotest.com']
# strSubJect = 'test email - text with image'
# eh = EmailHandler(smtpserver,username,password)
# imgpath = "D:\images\cropper.jpg"
# imgpath2 = "D:\images\picture.jpg"
# # eh.sendemail(strFrom,strTo,"text mail","Hi it's David, this is a test maill-----1","<h2>test html content</h2>")
# eh.sendemail(strFrom,strTo,"image mail","Hi it's David,\n this is a test maill-----2","<h2>test html content</h2>", [imgpath,imgpath2], listCc=strCc)
# # eh.sendemail(strFrom,strTo,"image mail","Hi it's David, this is a test maill-----2",listImagePath=[imgpath])