Flask:邮件扩展
邮件扩展
在开发过程中,很多应用程序都需要通过邮件提醒用户,Flask的扩展包Flask-Mail通过包装了Python内置的smtplib包,可以用在Flask程序中发送邮件。
Flask-Mail连接到简单邮件协议(Simple Mail Transfer Protocol,SMTP)服务器,并把邮件交给服务器发送。
设置邮箱授权码
如下示例,通过开启 QQ 邮箱验证 SMTP 服务设置,发送邮件:
#coding:utf-8from flask import Flask,render_template
from flask_mail import Mail, Message
from threading import Thread
app = Flask(__name__)
# 配置邮件:服务器/端口/安全套接字层/邮箱名/授权码
app.config['MAIL_SERVER'] = "smtp.126.com"
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = "furuiyang@126.com"
app.config['MAIL_PASSWORD'] = "19940414"
app.config['MAIL_DEFAULT_SENDER'] = 'FlaskAdmin<furuiyang@126.com>'
mail = Mail(app)
def async_send_email(app, msg):
with app.app_context():
try:
mail.send(msg)
except Exception as e:
print e
def send_email_thread(subject, to, content):
msg = Message(subject=subject, recipients=[to], body=content)
thread = Thread(target=async_send_email,args=(app, msg))
thread.start()
return thread
@app.route('/')
def index():
return '<a href="%s">发送邮件</a>' % url_for('send_email')
@app.route('/send_email')
def send_email():
send_email_thread('我是邮件主题', to='furuiyang@126.com', content='我是邮件内容哈哈')
return '发送中...'
if __name__ == '__main__':
app.run()
众多python培训视频,尽在python学习网,欢迎在线学习!
本文转自:https://blog.csdn.net/Enjolras_fuu/article/details/82793428
以上是 Flask:邮件扩展 的全部内容, 来源链接: utcz.com/z/540727.html