Flask 邮件发送

欢迎关注小婷儿的博客:

csdnhttps://blog.csdn.net/u010986753

博客园:http://www.cnblogs.com/xxtalhr/

 

有问题请在博客下留言或加QQ群:483766429 或联系作者本人 QQ 87605025

 

OCP培训说明连接:https://mp.weixin.qq.com/s/2cymJ4xiBPtTaHu16HkiuA

OCM培训说明连接:https://mp.weixin.qq.com/s/7-R6Cz8RcJKduVv6YlAxJA

 

小婷儿的python正在成长中,其中还有很多不足之处,随着学习和工作的深入,会对以往的博客内容逐步改进和完善哒。

小婷儿的python正在成长中,其中还有很多不足之处,随着学习和工作的深入,会对以往的博客内容逐步改进和完善哒。

小婷儿的python正在成长中,其中还有很多不足之处,随着学习和工作的深入,会对以往的博客内容逐步改进和完善哒。

重要的事说三遍。。。。。。

 

 

    wpsBA92.tmp    wpsBA93.tmp

 

一、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

 

 

原文地址:https://www.cnblogs.com/pythonbao/p/9064143.html