Как отправить электронное письмо с использованием email_user, содержащего HTML и CSS в Python Django? - PullRequest
0 голосов
/ 20 сентября 2018

Я отправляю пользователю ссылку на активацию на его зарегистрированный адрес электронной почты для моего блога.Я использую следующие строки кода для отправки электронной почты в моем представлении регистрации.Я не использую EmailMultiAlternatives или send_email, потому что я создаю уникальный токен для пользователя, который регистрируется, и я хочу использовать email_user, который автоматически позаботится о адресе и адресе электронной почты: -

current_site = get_current_site(request)
subject = 'Activate Your Account'
message = render_to_string('accounts/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),
            })
message.content_subtype = "html"
user.email_user(subject, message)

IЯ добавил html и css в мой шаблон account_activation_email.html, как показано ниже: -

{% autoescape off %}

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Activate your SaralGyaan account</title>

    <style type="text/css" rel="stylesheet" media="all">

    [styles go there not shown due to beverity]
    </style>
  </head>
  <body>
    <span class="preheader">Use this link to activate your SaralGyaan account. The link is only valid for 24 hours.</span>
    <table class="email-wrapper" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td align="center">
          <table class="email-content" width="100%" cellpadding="0" cellspacing="0">
            <tr>
              <td class="email-masthead">
                <a href="https://saralgyaan.com" class="email-masthead_name">
        SaralGyaan
      </a>
              </td>
            </tr>
            <!-- Email Body -->
            <tr>
              <td class="email-body" width="100%" cellpadding="0" cellspacing="0">
                <table class="email-body_inner" align="center" width="570" cellpadding="0" cellspacing="0">
                  <!-- Body content -->
                  <tr>
                    <td class="content-cell">
                      <h1>Hi {{user.get_full_name}},</h1>
                      <p>Thank you for registering your SaralGyaan's account. Please click the link below to activate your account. <strong>This link is only valid for the next 24 hours.</strong></p>
                      <!-- Action -->
                      <table class="body-action" align="center" width="100%" cellpadding="0" cellspacing="0">
                        <tr>
                          <td align="center">
                            <!-- Border based button
                       https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design -->
                            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                              <tr>
                                <td align="center">
                                  <table border="0" cellspacing="0" cellpadding="0">
                                    <tr>
                                      <td>
                                        <a href="{{ protocol }}://{{ domain }}{% url 'activate' uidb64=uid token=token %}" class="button button--green" target="_blank">Activate your account</a>
                                      </td>
                                    </tr>
                                  </table>
                                </td>
                              </tr>
                            </table>
                          </td>
                        </tr>
                      </table>
                      <p> If you have not created an account, please ignore this email or <a href="mailto:support@saralgyaan.com">contact support</a> if you have questions.</p>
                      <p>Thanks,
                        <br>The SaralGyaan Team</p>
                      <!-- Sub copy -->
                      <table class="body-sub">
                        <tr>
                          <td>
                            <p class="sub">If you’re having trouble with the button above, copy and paste the URL below into your web browser.</p>
                            <p class="sub">{{ protocol }}://{{ domain }}{% url 'activate' uidb64=uid token=token %}</p>
                          </td>
                        </tr>
                      </table>
                    </td>
                  </tr>
                </table>
              </td>
            </tr>
            <tr>
              <td>
                <table class="email-footer" align="center" width="570" cellpadding="0" cellspacing="0">
                  <tr>
                    <td class="content-cell" align="center">
                      <p class="sub align-center">&copy; 2018 SaralGyaan. All rights reserved.</p>
                      <p class="sub align-center">
                        [SaralGyaan]
                      </p>
                    </td>
                  </tr>
                </table>
              </td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
  </body>
</html>

Но полученное письмо не является его HTML-версией, а представляет собой простой текст.В этом HTML-коде нет ошибки, так как я использую то же самое с моей электронной почтой для сброса пароля, и она там работает нормально.

1 Ответ

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

Вы не можете отправить HTML один в электронном письме.HTML отправляется как альтернатива простому тексту.

Используйте html_message для отправки html-части и message для отправки в виде простого текста.

message = render_to_string('template.txt', ...)
html_message = render_to_string('textmplate.html', ...)
...