django内置password_reset更改send_email的连接

时间:2018-10-29 11:55:33

标签: django django-forms django-views django-contrib django-anymail

在我的应用程序中,我正在使用内置的身份验证视图。我还将使用django-anymail的邮戳连接用于某些用户电子邮件通知。

Example: 

email_backend = get_connection('anymail.backends.postmark.EmailBackend')
   mail = EmailMessage(
   subject=subject,
   body=message,
   to=[settings.DEFAULT_FROM_EMAIL],
   connection=email_backend
   )

我想更改我在PasswordResetView中发送电子邮件的连接。有什么方法可以像我给html_email_template_name='...'success_url='...'一样在PasswordResetView.as_view()中提供关键字参数吗?还是我必须重写PasswordResetView?

1 个答案:

答案 0 :(得分:1)

您不必更改PasswordResetView,但必须创建一个自定义PasswordResetForm,然后可以将其作为关键字参数传递给PasswordResetView.as_view()

如果查看PasswordResetView的源代码,您会发现它实际上并没有发送电子邮件本身。电子邮件的发送是PasswordResetForm.save()的一部分,它调用PasswordResetForm.send_mail()

您可以继承PasswordResetForm并覆盖.send_mail()以使用您的自定义电子邮件后端:

from django.contrib.auth.forms import PasswordResetForm

class PostmarkPasswordResetForm(PasswordResetForm):
    def send_mail(self, subject_template_name, email_template_name,
                  context, from_email, to_email, html_email_template_name=None):
        """
        Send a django.core.mail.EmailMultiAlternatives to `to_email` using
        `anymail.backends.postmark.EmailBackend`.
        """
        subject = loader.render_to_string(subject_template_name, context)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = loader.render_to_string(email_template_name, context)

        email_backend = get_connection('anymail.backends.postmark.EmailBackend')

        email_message = EmailMultiAlternatives(subject, body, from_email, [to_email], connection=email_backend)
        if html_email_template_name is not None:
            html_email = loader.render_to_string(html_email_template_name, context)
            email_message.attach_alternative(html_email, 'text/html')

        email_message.send()