Flask:邮件扩展

1,355次阅读
没有评论

Flask:邮件扩展

邮件扩展

在开发过程中,很多应用程序都需要通过邮件提醒用户,Flask的扩展包Flask-Mail通过包装了Python内置的smtplib包,可以用在Flask程序中发送邮件。

Flask-Mail连接到简单邮件协议(Simple Mail Transfer Protocol,SMTP)服务器,并把邮件交给服务器发送。

设置邮箱授权码

Flask:邮件扩展

如下示例,通过开启 QQ 邮箱验证 SMTP 服务设置,发送邮件:

#coding:utf-8
from 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()
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-07-09发表,共计1242字。
新手QQ群:570568346,欢迎进群讨论 Python51学习