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.
software_DjangoBlog/src/comments/utils.py

60 lines
2.6 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
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):
"""
功能:发送评论相关的通知邮件。
参数:
comment: 当前的评论对象,包含评论内容、作者信息、文章信息等。
"""
# 获取当前站点的域名
site = get_current_site().domain
# 定义邮件主题
subject = _('Thanks for your comment') # 邮件主题,支持多语言
# 构造文章的绝对 URL
article_url = f"https://{site}{comment.article.get_absolute_url()}"
# 构造邮件内容HTML 格式),感谢用户的评论
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_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)