代码之家  ›  专栏  ›  技术社区  ›  mastisa

如何在django电子邮件用户中将内容子类型更改为html

  •  1
  • mastisa  · 技术社区  · 6 年前

    我在这张确认表上看到了关于django的邮件 tutorial answer 如何在django发送html电子邮件。在本教程的电子邮件发送方法中,有没有办法将内容子类型更改为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)
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   mastisa    6 年前

    我试着得到我的答案,希望它能帮助别人。

    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 :