import logging from django.utils.translation import gettext_lazy as _ from djangoblog.utils import get_current_site from djangoblog.utils import send_email logger = logging.getLogger(__name__) def send_comment_email(comment): """ 当用户发表评论后,给评论者发送邮件通知; 如果该评论是回复别人的,则同时给被回复的用户发送提醒邮件。 """ # 获取当前站点域名 site = get_current_site().domain # 邮件主题 subject = _('Thanks for your comment') # 构造文章访问 URL(以便用户点进查看) article_url = f"https://{site}{comment.article.get_absolute_url()}" # 给评论者自己发送的邮件内容 html_content = _("""

Thank you very much for your comments on this site

You can visit %(article_title)s to review your comments, Thank you again!
If the link above cannot be opened, please copy this link to your browser. %(article_url)s""") % { 'article_url': article_url, 'article_title': comment.article.title } # 收件人 = 评论的作者本人 tomail = comment.author.email # 发送邮件 send_email([tomail], subject, html_content) try: # 如果该评论存在父评论(说明是回复行为) if comment.parent_comment: # 给被回复的人发送通知邮件 html_content = _("""Your comment on %(article_title)s
has received a reply.
%(comment_body)s
go check it out!
If the link above cannot be opened, please copy this link to your browser. %(article_url)s """) % { 'article_url': article_url, 'article_title': comment.article.title, 'comment_body': comment.parent_comment.body } # 父评论的作者邮箱 tomail = comment.parent_comment.author.email # 向被回复者发送邮件 send_email([tomail], subject, html_content) except Exception as e: # 出现错误则记录日志,但不影响评论正常流程 logger.error(e)