# 导入日志模块,用于记录程序运行中的信息和错误
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. 若该评论是回复其他评论的(即有父评论),则向被回复的评论者发送回复通知邮件
"""
# 获取当前站点的域名(如example.com)
site = get_current_site().domain
# 邮件主题:感谢评论(支持多语言)
subject = _('Thanks for your comment')
# 构建评论所属文章的完整URL(包含协议和域名)
article_url = f"https://{site}{comment.article.get_absolute_url()}"
# 构建给评论者的邮件内容(HTML格式,支持多语言)
# 使用占位符替换文章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格式,支持多语言)
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)