Как изменить content_subtype на html в django email_user - PullRequest
0 голосов
/ 09 сентября 2018

Я читал об электронной почте подтверждение django из этого учебника . Теперь мне нужно отправить html почту не простой строкой. Я прочитал этот ответ о том, как отправить HTML письмо по электронной почте в 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)

1 Ответ

0 голосов
/ 10 сентября 2018

Я пытался получить ответ, надеюсь, он может кому-то помочь.

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

...