import logging
from django.utils.translation import gettext_lazy as _
from djangoblog.utils import get_current_site
from djangoblog.utils import send_email
# 获取当前模块的 logger 实例,用于记录日志
logger = logging.getLogger(__name__)
def send_comment_email(comment):
# 获取当前站点的域名(如 example.com)
site = get_current_site().domain
# 邮件主题(支持国际化)
subject = _('Thanks for your comment')
# 构造文章的完整绝对 URL(使用 HTTPS)
article_url = f"https://{site}{comment.article.get_absolute_url()}"
# 构造发送给评论作者的 HTML 邮件内容
# 内容包含感谢语、文章链接和标题,并支持变量替换
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)