(5) 第5章:flask_mail 模块,邮件发送

from flask_mail import Mail

电子邮件的发送
**mail = Mail()**一般在app创建的模块去创建邮件对象的实例,然后在app上注册
如要创建新的线程去实现邮件的异步发送,因为flask线程是隔离的
要获取真正的flask核心对象则要 app = current_app._get_current_object() # 获取真正的flask核心对象
下面是实现邮件异步发送的代码

from threading import Thread
from flask import current_app, render_template
from flask_mail import Message
from app import mail
# 异步邮件发送
# 将发送邮件改造成多线程的send_async_email, 运行后发现send_email中current_app正常,
# 但是在send_async_email中app会是notfound。导致的原因就是在之前flask核心机制的博文中说的
# current_app是代理的核心对象,线程隔离的。我们需要拿到真正的核心对象并传入send_async_email:

def send_aysnc_email(app, msg):
	# App_Context 的栈Local Stack是线程隔离的,在新线程里栈顶为空,需要手动入栈
	with app.app_context():
	    try:
	        mail.send(msg)
	    except Exception as e:
	        print('邮件发送失败')
	        raise e

# 传入参数 接受者 邮件主题  邮箱模版  邮箱内容
def send_mail(to, subject, template, **kwargs):
	# msg = Message('测试邮件',sender='[email protected]',body='Test',recipients=['[email protected]'])
	# mail.send(msg)
	# sender表示发送邮件的邮箱
	# recipients 表示接受邮件的人的列表,可发送给多个用户
	# 邮件的信息  如发送人  接收人  主题
	
	#Message有一个body的参数,可编辑邮件发送的文本
	msg = Message(subject, sender=current_app.config['MAIL_USERNAME'], recipients=[to])
	
	# html表示发送页面,传送模板进去和参数
	msg.html = render_template(template, **kwargs)  # 邮件的模版和内容
	# mail.send(msg) #发送
	# current_app是代理对象,在当前线程下有指向
	# 但是在新开启的线程中就没了,因为LocalProxy是线程隔离的
	# 得到flask核心对象 放到其他线程使用
	app = current_app._get_current_object()  # 获取真正的flask核心对象
	# App_Context 的栈Local Stack是线程隔离的,在新线程里栈顶为空,需要手动入栈
	thr = Thread(target=send_aysnc_email, args=(app, msg))
	thr.start()

猜你喜欢

转载自blog.csdn.net/weixin_42504453/article/details/83583663