Flask-Mail可以连接到配置中的SMTP服务器,进行邮件发送,如果没有进行SMTP服务器的配置,将会默认连接到localhost上的
一.配置及初始化
(1)flask应用配置
#配置选项 MAIL_SERVER = 'smtp.qq.com' #邮件服务器 MAIL_PORT = 25 #端口 MAIL_USE_TLS = False#传输层安全协议 MAIL_USE_SSL = False #安全套接层协议 MAIL_USERNAME = 'you' #账号 MAIL_PASSWORD = 'your-password'#密码
(2)初始化
from flask.ext.mail import Mail from flask import Flask app = Flask(__name__) mail = Mail(app)
二.发送邮件
from flask.ext.mail import Message from app import mail #创建一封邮件 msg = Message("邮件主题", sender='skkg@qq.com', recipients=['123@qq.com','321@qq.com'] ) msg.body = '文本内容' msg.html = '<b>HTml内容</b>' #发送邮件,flask-mail需要在current_app上下文中发送邮件 with app.app_context(): mail.send(msg)
辅助邮件发送函数
def send_email(to, subject, template, **kwargs): app = current_app._get_current_object() msg = Message(subject, sender= 'skkg@qq.com', recipients=[to]) msg.body = render_template(template + '.txt', **kwargs) msg.html = render_template(template + '.html', **kwargs) #在新线程中发送邮件 thr = Thread(target=send_async_mail, args=[app, msg]) thr.start() return thr #异步发送邮件,加快速度 def send_async_mail(app, msg): with app.app_context(): mail.send(msg)