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 (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):
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.'
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgContent = strMsgText.replace("n","<br>") if strMsgText else ""
msgContent += "<br>" + strMsgHtml if strMsgHtml else ""
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)
for i,imgpath in enumerate(listImagePath):
fp = open(imgpath, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image{count}>'.format(count=i))
msgRoot.attach(msgImage)
else:
msgText = MIMEText(msgContent, 'html')
msgAlternative.attach(msgText)
return msgRoot
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)))
近期评论