You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DjangoBlog/comments/utils.py

73 lines
4.0 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 赵瑞萍:评论邮件通知模块,用于评论提交后发送邮件通知
# 核心功能:向评论者发送感谢邮件,向被回复者发送评论回复通知,支持多语言和链接跳转
# 赵瑞萍:导入日志模块,记录邮件发送过程中的信息和异常
import logging
# 赵瑞萍导入Django国际化翻译工具实现邮件内容多语言支持
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):
"""
赵瑞萍:发送评论相关邮件通知的核心函数
分两种场景发送邮件:
1. 向当前评论的发布者发送感谢评论邮件
2. 若当前评论是回复其他评论(有父评论),向被回复者发送回复通知邮件
参数comment - 已保存的Comment模型实例包含评论、作者、关联文章、父评论等信息
"""
# 赵瑞萍获取当前站点的域名如www.example.com用于构建完整的文章访问链接
site = get_current_site().domain
# 赵瑞萍:邮件主题(支持多语言,根据项目语言配置自动切换)
subject = _('Thanks for your comment')
# 赵瑞萍构建评论所属文章的完整URLHTTPS协议+域名+文章绝对路径)
article_url = f"https://{site}{comment.article.get_absolute_url()}"
# 赵瑞萍构建给评论者的感谢邮件内容HTML格式支持超链接
# 使用字符串格式化替换占位符注入文章URL和标题
html_content = _("""<p>Thank you very much for your comments on this site</p>
You can visit <a href="%(article_url)s" rel="bookmark">%(article_title)s</a>
to review your comments,
Thank you again!
<br />
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格式告知其评论收到回复
html_content = _("""Your comment on <a href="%(article_url)s" rel="bookmark">%(article_title)s</a><br/> has
received a reply. <br/> %(comment_body)s
<br/>
go check it out!
<br/>
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)