如何在 Django email_user 中将 content_subtype 更改为 html

How to change content_subtype to html in django email_user

我阅读了有关如何在 django 中发送 html 电子邮件的 tutorial. Now I need to send html mail not a simple string. I read this 的 django 电子邮件确认表单。在本教程的电子邮件发送方法中,有没有办法将 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: If html_message is provided, the resulting email will be a multipart/alternative email with message as the text/plain content type and html_message as the text/html content type