django +使用django-registration以html发送电子邮件

Asi*_*nox 11 email django django-templates django-registration

即时通讯使用django-registration,一切都很好,确认电子邮件是以纯文本形式发送的,但我知道我已修复并正在发送html,但我有一个垃圾问题...... html代码显示:

<a href="http://www.example.com/accounts/activate/46656b86eefc490baf4170134429d83068642139/">http://www. example.com/accounts/activate/46656b86eefc490baf4170134429d83068642139/</a>
Run Code Online (Sandbox Code Playgroud)

我不需要像...那样显示HTML代码

任何的想法?

谢谢

bpi*_*rre 27

为避免修补django-registration,您应该使用proxy = True扩展RegistrationProfile模型:

models.py

class HtmlRegistrationProfile(RegistrationProfile):
    class Meta:
        proxy = True
    def send_activation_email(self, site):
        """Send the activation mail"""
        from django.core.mail import EmailMultiAlternatives
        from django.template.loader import render_to_string

        ctx_dict = {'activation_key': self.activation_key,
                    'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                    'site': site}
        subject = render_to_string('registration/activation_email_subject.txt',
                                   ctx_dict)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())

        message_text = render_to_string('registration/activation_email.txt', ctx_dict)
        message_html = render_to_string('registration/activation_email.html', ctx_dict)

        msg = EmailMultiAlternatives(subject, message_text, settings.DEFAULT_FROM_EMAIL, [self.user.email])
        msg.attach_alternative(message_html, "text/html")
        msg.send()
Run Code Online (Sandbox Code Playgroud)

在您的注册后端,只需使用HtmlRegistrationProfile而不是RegistrationProfile.

  • 如何将后端设置为HtmlRegistration配置文件而不是RegistrationProfile? (10认同)

Pau*_*jan 14

我建议同时发送文本版和html版.查看django-registration的models.py:

send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.user.email])
Run Code Online (Sandbox Code Playgroud)

而是从文档中做一些事情http://docs.djangoproject.com/en/dev/topics/email/#sending-alternative-content-types

from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
Run Code Online (Sandbox Code Playgroud)