我在tutorial中阅读了有关django电子邮件确认表格的信息。现在,我需要发送html邮件,而不是简单的字符串。我阅读了有关如何在Django中发送html电子邮件的answer信息。在本教程的电子邮件发送方法中,是否可以将content_subtype更改为html?或任何其他方式以这种方式发送html邮件?

current_site = get_current_site(request)
subject = 'Activate Your Account'
message = render_to_string('account_activation_email.html', {
    'user': user,
    'domain': current_site.domain,
    'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
    'token': account_activation_token.make_token(user),
    })
user.email_user(subject, message)

最佳答案

我尝试并得到了答案,希望它可以帮助其他人。

email_user函数是这样的:

def email_user(self, subject, message, from_email=None, **kwargs):
    """Send an email to this user."""
    send_mail(subject, message, from_email, [self.email], **kwargs)


这是send_mail函数:

def send_mail(subject, message, from_email, recipient_list,
              fail_silently=False, auth_user=None, auth_password=None,
              connection=None, html_message=None):
    """
    Easy wrapper for sending a single message to a recipient list. All members
    of the recipient list will see the other recipients in the 'To' field.

    If auth_user is None, use the EMAIL_HOST_USER setting.
    If auth_password is None, use the EMAIL_HOST_PASSWORD setting.

    Note: The API for this method is frozen. New code wanting to extend the
    functionality should use the EmailMessage class directly.
    """
    connection = connection or get_connection(
       username=auth_user,
       password=auth_password,
       fail_silently=fail_silently,
    )
    mail = EmailMultiAlternatives(subject, message, from_email, recipient_list, connection=connection)
    if html_message:
        mail.attach_alternative(html_message, 'text/html')

    return mail.send()


首先我有一个html_message属性,我认为它的处理方式类似于电子邮件的附件,但我对其进行了测试,并且它可以正常工作。

这是我发送HTML电子邮件的代码:

        current_site = get_current_site(request)
        subject = 'Activate Your Account'
        message = render_to_string('account_activation_email.html', {
            'user': user,
            'domain': current_site.domain,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
            'token': account_activation_token.make_token(user),
        })
        user.email_user(subject, '', html_message=message)


django docs


  html_message:如果提供了html_message,则生成的电子邮件将是多部分/替代电子邮件,其消息为文本/纯内容类型,而html_message为文本/ html内容类型

关于python - 如何在Django email_user中将content_subtype更改为html,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52244151/

10-09 08:21
查看更多