项目里一个模块,重新封装了python的smtplib和django的template
主要功能:
-
支持多用户接受
-
支持模板
-
良好的处理了中文问题
代码如下:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
#
__author__="Fred"
__date__ ="$2010-5-31 17:15:35$"
import smtplib, base64
from django.template import loader, Context
CHARSET = 'utf-8'
FROM_ADD = 'xxxxxx@163.com'
SMTP_SERVER = 'smtp.163.com'
SMTP_USER = 'xxxxx'
SMTP_PASS = 'xxxxx'
class SendMail:
u'''
邮件发送模块,此模块运行使用django模块来发送邮件
参数介绍(*必填):
subject *邮件主题
template *邮件模板位置
context *邮件模板上下文
to_addr *目的地址,允许发给多人,格式为['test@examp.com','test2@example',......]
smtp_server 发件服务器地址
smtp_server_port 发件服务器端口号
from_addr 发信地址
from_addr_name 发信人名称
user 发件箱登录用户名
pass 发件箱登录密码
e.g:
from ureg.helper import SendMail
mail = SendMail('test','email/register.html',{'tmp_code':'123'},['ad@fengsage.cn'])
mail.send_mail()
u'''
def __init__(self,subject,template,context,to_addr,smtp_server=SMTP_SERVER, smtp_server_port = 25 ,from_addr=FROM_ADD,from_addr_name=u'Mytut视频网',user=SMTP_USER, passwd=SMTP_PASS):
self.subject = subject
self.template = template
self.context = context
self.to_addr = to_addr
self.from_addr = from_addr
self.from_addr_name = from_addr_name
self.username = user
self.password = passwd
self.smtp_server_port = smtp_server_port
self.mailserver = smtp_server
def send_mail(self):
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email import Utils
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = self.subject
msgRoot['From'] = self.named(self.from_addr, self.from_addr_name)
if len(self.to_addr) == 1:
msgRoot['To'] = self.to_addr[0]
else:
msgRoot['To'] = Utils.COMMASPACE.join(self.to_addr)
pass
msgRoot['Date'] = Utils.formatdate()
# 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)
#根据模板生成html
html = self.render(self.template, self.context).encode('utf-8')
msgText = MIMEText(html,'html',_charset='utf-8')
msgAlternative.attach(msgText)
smtp = smtplib.SMTP(self.mailserver,self.smtp_server_port)
smtp.login(self.username, self.password)
result = smtp.sendmail(self.from_addr, self.to_addr, msgRoot.as_string())
smtp.quit()
def render(self,template,context):
u'''
读取模板内容,并赋值
u'''
if template:
t = loader.get_template(template)
return t.render(Context(context))
return context
def named(self,mail,name):
u'''
格式化右键发信/收信格式
e.g fredzhu <me@fengsage.cn>
u'''
if name:
return '%s <%s>' % (name,mail)
return mail
使用方法:
mail = SendMail(USER_REGISTER,'email/register.html',{'tmp_code':tmp_code,'tmp_user':username},[email])
mail.send_mail()
近期评论