使用flask-mail扩展
pip install flask-mail
1.配置邮箱
(1)我这里使用的是163邮箱,首先需要打开邮箱,找到下图这里
(2)开启SMTP服务,然后申请授权密码,需要绑定手机号
(3)163的服务器地址和端口如下
2.配置app.config
这里把用户名和密码都配进了本地的系统变量中
from flask import Flask
import os
app=Flask(__name__)
app.config['MAIL_SERVER']='smtp.163.com'
app.config['MAIL_PORT']=994
app.config['MAIL_USE_TLS']=False
app.config['MAIL_USE_SSL']=True
app.config['MAIL_USERNAME']=os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD']=os.environ.get('MAIL_PASSWORD')
3.初始化邮箱
flask_mail会自动帮我们创建好SMTP服务器
from flask_mail import Mail,Message
mail=Mail(app)
4.同步方式发送邮件
@app.route('/sendMail')
def sendMail():
msg=Message('test message',sender=os.environ.get('MAIL_USERNAME'),recipients=['xxxxxx@qq.com'])
msg.body='this is body!'
msg.html='<b>HTML</b> body'
with app.app_context():
mail.send(msg)
return '<h1>发送成功!</h1>'
5.异步方式发送邮件
def send_async_mail(app,msg):
with app.app_context():
mail.send(msg)
def send_mail(to,subject,template,**kwargs):
msg=Message('async test '+subject,sender=os.environ.get('MAIL_USERNAME'),recipients=[to])
msg.body=render_template(template+'.txt',**kwargs)
msg.body = render_template(template+'.html', **kwargs)
th=Thread(target=send_async_mail,args=[app,msg])
th.start()
return th
@app.route('/sendSync')
def send_async():
to='xxxxxxxx@qq.com'
subject='ASYNC'
template='test'
send_mail(to,subject,template)
return '<h1>ASYNC 发送成功!</h1>'
6.完整代码
# coding:utf-8
from flask import Flask,render_template
import os
from flask_mail import Mail,Message
from threading import Thread
app=Flask(__name__)
app.config['MAIL_SERVER']='smtp.163.com'
app.config['MAIL_PORT']=994
app.config['MAIL_USE_TLS']=False
app.config['MAIL_USE_SSL']=True
app.config['MAIL_USERNAME']=os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD']=os.environ.get('MAIL_PASSWORD')
mail=Mail(app)
def send_async_mail(app,msg):
with app.app_context():
mail.send(msg)
def send_mail(to,subject,template,**kwargs):
msg=Message('async test '+subject,sender=os.environ.get('MAIL_USERNAME'),recipients=[to])
msg.body=render_template(template+'.txt',**kwargs)
msg.body = render_template(template+'.html', **kwargs)
th=Thread(target=send_async_mail,args=[app,msg])
th.start()
return th
@app.route('/sendSync')
def send_async():
to='xxxxxxx@qq.com'
subject='ASYNC'
template='test'
send_mail(to,subject,template)
return '<h1>ASYNC 发送成功!</h1>'
@app.route('/sendMail')
def sendMail():
msg=Message('test message',sender=os.environ.get('MAIL_USERNAME'),recipients=['xxxxxxx@qq.com'])
msg.body='this is body!'
msg.html='<b>HTML</b> body'
with app.app_context():
mail.send(msg)
return '<h1>发送成功!</h1>'
if __name__=='__main__':
app.run(debug=True)