赞
踩
pip install flask-mail
(1)我这里使用的是163邮箱,首先需要打开邮箱,找到下图这里
(2)开启SMTP服务,然后申请授权密码,需要绑定手机号
(3)163的服务器地址和端口如下
这里把用户名和密码都配进了本地的系统变量中
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')
flask_mail会自动帮我们创建好SMTP服务器
from flask_mail import Mail,Message
mail=Mail(app)
@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>'
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>'
# 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)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。