from threading import Thread
from . import mail
from flask import render_template, current_app
from flask_mail import Message

def send_async_email(app, msg):
    """
        todo 线程中发送邮件
    :param app: app
    :param msg: 发送的信息
    :return: 发送邮件
    """
    with app.app_context():
        mail.send(msg)


def send_email(to, subject, tempate, **kwargs):
    """
        todo 发送邮件信息
    :param to: 接收者
    :param subject: 邮件主题
    :param tempate: 邮件渲染模板
    :param kwargs: 参数
    :return: 线程对象
    """

    app = current_app._get_current_object()

    msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
                  sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
    # msg.body = render_template(tempate + ".txt", **kwargs)
    msg.html = render_template(tempate + ".html", **kwargs)

    # todo 使用多线程发送邮件
    thread = Thread(target=send_async_email, args=(app, msg))
    thread.start()
    return thread
