Flask 邮件发送

  • 2019 年 10 月 10 日
  • 笔记

今天小婷儿给大家分享的是Flask 邮件发送。

Flask 邮件发送

一、Flask 邮件发送

from flask import Flask, render_template, current_app

from flask_script import Manager

from flask_mail import Mail, Message

from threading import Thread

app = Flask(__name__)

# 配置邮箱服务器

app.config['MAIL_SERVER'] = 'smtp.163.com'

# 邮箱用户

app.config['MAIL_USERNAME'] = '邮箱@163.com'

# 用户密码

app.config['MAIL_PASSWORD'] = '邮箱密码'

# 创建Mail对象

mail = Mail(app)

def async_send_mail(app, msg):

# 邮件发送需要在程序上下文中进行,

# 新的线程中没有上下文,需要手动创建

with app.app_context():

mail.send(msg)

# 封装函数发送邮件

def send_mail(subject, to, template, **kwargs):

# 从代理中获取代理的原始对象

app = current_app._get_current_object()

# 创建用于发送的邮件消息对象

msg = Message(subject=subject, recipients=[to],

sender=app.config['MAIL_USERNAME'])

# 设置内容

msg.html = render_template(template, **kwargs)

# 发送邮件

# mail.send(msg)

thr = Thread(target=async_send_mail, args=[app, msg])

thr.start()

return '邮件已发送'

#路由配置

@app.route('/')

def index():

# 调用函数发送邮件

send_mail('账户激活', '邮件接收者地址', 'activate.html', username='xenia')

return '邮件已发送'

manager = Manager(app)

if __name__ == '__main__':

manager.run()

二、flask-mail

说明:

专门用于发送邮件的扩展库,使用非常方便

安装:

`pip install flask-mail`

使用:

配置邮件发送选项

创建邮件对象

创建消息对象

使用邮件对象发送消息

封装函数发送邮件

将邮件发送的操作通过一个函数完成

使用者只需要在合适的地方调用即可

异步发送邮件

原因:受限于网络的原因,可能会出现长时间等待的情况

解决:在新的线程中完成邮件的发送

问题:邮件发送需要程序上下文,而新的线程中没有,因此需要手动创建程序上下文

理解:循环引用程序实例的解决方案是使用current_app代替app