Flask-Mail

说明

  • flask-mail是专门用来邮件发送的扩展库

安装

  • pip install flask-mail

文档

使用

from flask_mail import Mail, Message
import os

# 邮件相关配置
# 服务器
app.config['MAIL_SERVER'] = 'smtp.1000phone.com'
# 端口号
app.config['MAIL_PORT'] = 465
# 加密传输
app.config['MAIL_USE_SSL'] = True
# 用户名
app.config['MAIL_USERNAME'] = 'lijie@1000phone.com'
# 密码
app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD', '123456')

# 创建发送邮件对象
mail = Mail(app)

@app.route('/send/')
def send():
    # 创建邮件对象
    msg = Message(
        subject='账户激活',
        recipients=['1415532462@qq.com'],
        html='<h2>恭喜你,中奖了!</h2>',
        sender=app.config['MAIL_USERNAME']
    )
    # 发送邮件
    mail.send(msg)
    return '邮件已发送'
  • 封装函数发送邮件
def send_mail(subject, to, template, *args, **kwargs):
    if isinstance(to, list):
        recipients = to
    elif isinstance(to, str):
        recipients = to.split(',')
    else:
        raise Exception('邮件接收者格式有误')
    # 渲染邮件模板得到邮件消息体
    html = render_template(template, *args, **kwargs)
    # 创建邮件对象
    msg = Message(
        subject=subject,
        recipients=recipients,
        html=html,
        sender=app.config['MAIL_USERNAME']
    )
    # 发送邮件
    mail.send(msg)
  • 异步发送邮件
# 异步发送函数
def async_send_mail(app, msg):
    # 邮件发送需要在线程上下文完成
    # 新建的线程没有上下文,需要手动创建线程上下文
    with app.app_context():
        # 在线程上下文中发送邮件
        mail.send(msg)

# 封装函数发送邮件
def send_mail(subject, to, template, *args, **kwargs):
    if isinstance(to, list):
        recipients = to
    elif isinstance(to, str):
        recipients = to.split(',')
    else:
        raise Exception('邮件接收者格式有误')
    # 渲染邮件模板得到邮件消息体
    html = render_template(template, *args, **kwargs)
    # 创建邮件对象
    msg = Message(
        subject=subject,
        recipients=recipients,
        html=html,
        sender=app.config['MAIL_USERNAME']
    )
    # 发送邮件
    # mail.send(msg)
    # 异步发送邮件
    thr = Thread(target=async_send_mail, args=(app, msg))
    # 启动线程
    thr.start()
    return thr

推荐

results matching ""

    No results matching ""