由于博客要支持评论,因此咱们须要在文章有了新评论后发邮件通知管理员。并且,当管理员回复了读者的评论后,也须要发送邮件提醒读者。html
为了方便读者使用示例程序,personalBlog中仍然使用Flask-Mail来发送邮件。读者在运行程序前须要在项目根目录内建立.env文件写入对应的环境变量,以便让发信功能正常工做。flask
由于邮件的内容很简单,咱们将直接在发信函数中写出正文内容,这里只提供了HTML正文。咱们有两个须要使用电子邮件的场景:app
一、当文章有新评论时,发送邮件给管理员;异步
二、当某个评论被回复时,发送邮件给被回复用户。async
为了方便使用,咱们在emails.py中分别为这两个使用场景建立了特定的发信函数,能够直接在视图函数中调用 。这些函数内部则经过咱们建立的通用发信函数send_email()来发送邮件,以下所示 :ide
personalBlog/emails.py: 提醒邮件函数函数
from flask import url_for def send_mail(subject, to, html): pass def send_new_comment_email(post): # blog.show_post是blog蓝本下的show_post视图函数 post_url = url_for('blog.show_post', post_id = post.id, _external = True) + '#comments' send_mail(subject = 'New comment', to = current_app.config['BLUEBLOG_ADMIN_EMAIL'], html = '<p>New comment in post <i>%s</i>, click the link below to check:</p>' '<p><a href="%s">%s</a></p>' '<p><small style = "color:#868e96">Do not reply this email.</small></p>' % (post.title, post_url, post_url)) def send_new_reply_email(comment): post_url = url_for('blog.show_post', post_id = comment.post_id, _external = True) + '#comments' send_mail(subject = 'New reply', to = comment.email, html = '<p>New reply for the comment you left in post <i>%s</i>, click the link below to check: </p>' '<p><a href="%s">%s</a></p>' '<p><small style="color: #868e96">Do not reply this email.</small></p>' % (comment.post.title, post_url, post_url))
send_new_comment_email()函数用来发送新评论提醒邮件。 咱们经过将url_for()函数的_external参数设为True来构建外部连接。连接尾部的#comments是用来跳转到页面评论部分的URL片断(URL fragment),comments是评论部分div元素的id值。这个函数接收表示文章的post对象做为参数,从而生成文章正文的标题和连接。post
URL片断又称片断标识符(fragment identifier),是URL中用来表示页面中资源位置的短字符,以#开头,对于HTML页面来讲,一个典型的示例是文章页面的评论区。假设评论区的div元素id为comment,若是咱们访问http://example.com/post/7#comment,页面加载完成后将会直接跳到评论部分。this
send_new_reply_email()函数则用来发送新回复提醒邮件。这个发信函数接收comment对象做为参数,用来构建邮件正文,所属文章的主键值经过comment.post_id属性获取,标题则经过comment.post.titlle属性获取。url
在personalBlog源码中,咱们没有使用异步的方式发送邮件,若是你但愿编写一个异步发送邮件的通用发信函数send_mail(),和以前介绍的基本相同,以下所示
from threading import Thread from flask import current_app from flask_mail import Message from personalBlog.extensions import mail def _send_async_mail(app, message): with app.app_context(): mail.send(message) def send_async_mail(subjecct, to, html): app = current_app._get_current_object() # 获取被代理的真实对象 message = Message(subjecct, recipients=[to], html = html) thr = Thread(target = _send_async_mail, args = [app, message]) thr.start() return thr
须要注意,由于咱们的程序是经过工厂函数建立的,因此实例化Thread类时,咱们使用代理对象current_app做为args参数列表中app的值。另外,由于在新建线程时须要真正的程序对象来建立上下文,因此不能直接传入current_app,而是传入current_app调用_get_current_app()方法获取的被代理的程序实例。