Python:邮件发送
1. 封装源码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Abstract: send mail
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
class Mail(object):
def __init__(self, smtp, user, pwd):
self.smtp = smtp
self.user = user
self.pwd = pwd
self.isauth= True
def parse_send(self, subject, content, plugin):
return subject, content, plugin
def send(self, subject, content, tolist, cclist=[], plugins =[]):
msg = MIMEMultipart()
msg.set_charset('utf-8')
msg['from'] = self.user
msg['to'] = ','.join(tolist)
if cclist:
msg['cc'] = ','.join(cclist)
msg['subject'] = subject
msg.attach( MIMEText(content,'html','utf-8'))
for plugin in plugins:
f = MIMEApplication(plugin['content'])
f.add_header('content-disposition','attachment',filename=plugin['subject'])
msg.attach(f)
s = smtplib.SMTP(self.smtp)
s.set_debuglevel(smtplib.SMTP.debuglevel)
if self.isauth:
s.docmd("EHLO %s"%self.smtp)
try:
s.starttls()
except smtplib.SMTPException,e:
pass
s.login(self.user,self.pwd)
r = s.sendmail(self.user,tolist,msg.as_string())
s.close()
return r
if __name__=="__main__" :
subject = '发送邮件测试'
content = '<font color="#0000FF">热门</color>'
plugins = [{'subject':'附件1.txt','content':'内容1'},{'subject':'附件2.txt','content':'内容2'}]
mail = Mail('smtp.exmail.qq.com','XX@126.com','12345678' )
tolist = ['xx@gmail.com']
cclist = []
mail.send(subject,content,tolist,cclist,plugins)
print 'duokan mail send'
2. 邮件发送模板
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Abstract: 定时任务
import os
import sys
import logging
import datetime
import threading,time
sys.path.append(os.path.dirname(os.path.split(os.path.realpath(__file__))[0]))
from conf.style_dic import DicMap
class EmailTemplate(object):
'''
Email邮件发送模板
'''
#简单table列表项模板
@staticmethod
def simple_template(self,tb_head,tb_head_indexs,rs):
content_list = []
content_list.append('<table width="100%" border="1"><thead><tr>')
for h_key in tb_head_indexs:
content_list.append('<th width="150" align="center">')
content_list.append(tb_head.get(h_key))
content_list.append('</th>')
content_list.append('</tr></thead><tbody>')
for record in rs:
content_list.append('<tr>')
for h_key in tb_head_indexs:
content_list.append('<td>')
val = record.get(h_key)
content_list.append(EmailTemplate.data2str(self,val))
content_list.append('</td>')
content_list.append('</tr>')
content_list.append('</tbody></table>')
if not rs:
content_list = []
return content_list
#简单txt列表项模板
@staticmethod
def simple_txt_template(self,tb_head,tb_head_indexs,rs):
content_list = []
content_list.append('\t')
for h_key in tb_head_indexs:
content_list.append(tb_head.get(h_key)+' ')
content_list.append('\r\n')
for record in rs:
content_list.append('\t')
for h_key in tb_head_indexs:
val = record.get(h_key)
content_list.append(EmailTemplate.data2str(self,val)+' ')
content_list.append('\r\n')
content_list.append('\r\n')
if not rs:
content_list = []
return content_list
#带简要综述表头模板
@staticmethod
def simple_head_template(self,tb_head,rs):
pass
@staticmethod
def head_condition_template(self,tb_head,rs):
content_list = []
content_list.append('<table width="100%" border="1"><thead><tr>')
h_keys = tb_head.keys()
for h_key in h_keys:
content_list.append('<th width="150" align="center">')
row_head = tb_head.get(h_key)
if row_head.find('&')==-1:
content_list.append(row_head)
else:
content_list.append(row_head.split('&')[0])
content_list.append('</th>')
content_list.append('</tr></thead><tbody>')
for record in rs:
content_list.append('<tr>')
for h_key in h_keys:
content_list.append('<td>')
row_head = tb_head.get(h_key)
if row_head.find('&')==-1:
content_list.append(EmailTemplate.data2str(self,record.get(h_key)))
else:
condition = row_head.find('&')[1].strip()
val = record.get(h_key)
content_list.append(EmailTemplate.data2str(self,val))
content_list.append('</td>')
content_list.append('</tr>')
content_list.append('</tbody></table>')
if not rs:
content_list = []
return content_list
#将各种数据类型的数据转换成字符串数据
@staticmethod
def data2str(self,val):
if str(type(val))==DicMap.DATA_TYPE_DATE:
val = val.strftime("%Y-%m-%d %X")
return val
if str(type(val))==DicMap.DATA_TYPE_LONG:
return str(val)
return val
#根据条件,将数据转换成条件值
@staticmethod
def condition2val(self,h_key,record,condition):
regexKey = 'key:'
regexEqual = '=='
equalKey = condition[condition.find(regexKey):condition.find(regexEqual)].split(':')[1]
#regexIf =
if __name__ == "__main__":
pass
3. 使用示例
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Abstract: 定时任务
import os
import sys
import urllib
import json
import logging
import datetime
import threading,time
sys.path.append(os.path.dirname(os.path.split(os.path.realpath(__file__))[0]))
from lib.mail import Mail
from tornado.template import Template,Loader
from conf.style_dic import DicMap
from model.moalarm import MoMailHead,MoMailContent,MoNoteHead,MoNoteContent
from service.mailtemplate import EmailTemplate
from model.mojob import MoJobTimer
class AlarmHandler(object):
'''
报警处理
目前报警类型为:短信(NOTE_SEND)、邮件(MAIL_SEND)
默认为邮件报警
'''
@staticmethod
def alarm(self,rs_head,rs,alarm_type,note_id,mail_id,timer_id):
logging.info("---->Alarm Info :Send Alarm Info. ")
#报警方式为邮件
if alarm_type==DicMap.ALARM_TYPE_MAIL:
logging.info("---->Send Type: Send Email. ")
MailHandler.toSend(self,rs_head,rs,mail_id,timer_id)
#报警方式为短信
elif alarm_type==DicMap.ALARM_TYPE_NOTE:
logging.info("---->Send Type: Send Note. ")
NoteHandler.toSend(self,rs,note_id)
else:
pass
class MailHandler(object):
@staticmethod
def toSend(self,rs_head,rs,mail_id,timer_id):
#发送邮件
logging.info("=====>total rows: %i ",len(rs))
m = MoMailHead.mgr(ismaster=True).one(mail_id)
is_package = m.get('is_package')
tolist = m.get('inbox_mails').split(',')
copytolist = m.get('copyto_mails').split(',')
rs_head_arr = rs_head.split(',')
tb_head = {head.split(':')[0]:head.split(':')[1] for head in rs_head_arr}
tb_head_indexs = [head.split(':')[0] for head in rs_head_arr]
if is_package==DicMap.YES:
content_list = EmailTemplate.simple_txt_template(self,tb_head,tb_head_indexs,rs)
else:
content_list = EmailTemplate.simple_template(self,tb_head,tb_head_indexs,rs)
if len(content_list)>0:
content = ''.join(content_list)
mail = Mail(m.get('smtp'),m.get('outbox_mail'),m.get('pwd'))
if is_package==DicMap.YES:
today_time = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M")
#file_name = today_time + str(m.title)
file_name = today_time
subject = "%s.txt" % file_name
plugins = [{'subject':subject,'content':content}]
mail.send(m.get('title'),'',tolist,copytolist,plugins)
else:
mail.send(m.get('title'),content,tolist,copytolist)
#记录邮件发送日志
timer = MoJobTimer.mgr(ismaster=True).one(timer_id)
t = MoMailContent.new()
t.head_id = m.id
t.timer_id = timer_id
t.timer_name = timer.name
t.send_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
t.send_content = ''.join(content_list)
t = t.save()
logging.info("---->close method: Send Email Method. ")
浙公网安备 33010602011771号