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

70 lines
3.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. 若该评论是回复其他评论的(即有父评论),则向被回复的评论者发送回复通知邮件
"""
# 获取当前站点的域名如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 = _("""<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)