默认情况下,将 Django 更改为使用 EmailMultiAlternatives 而不是 send_mail() (all-auth)

Change Django to use EmailMultiAlternatives instead of send_mail() by default (all-auth)

提问人:fmakawa 提问时间:8/23/2023 更新时间:8/23/2023 访问量:50

问:

所以我使用 django-all-auth 进行身份验证,并使用其内置功能来邮寄重置密码、确认注册等。我设计了包含图像的模板。对于常规电子邮件,我明确使用使用 EmailMultiAlternatives 而不是 send_mail() 的函数,因为它允许内联图像和背景图像。 然而,Django-all-auth 会自动使用 send_mail(),我的电子邮件到达时缺少图像。 如何覆盖它,以便它使用 EmailMultiAlternatives?

Django 电子邮件 django-allauth

评论


答:

0赞 fmakawa 8/23/2023 #1

我最终制作了一个适配器,它修改了帐户适配器 (allauth.account.adapter.DefaultAccountAdapter) 的send_mail和render_mail方法。

在其中,我通过调用的函数(logo_data 和 background_data)附加了我想要的图像。图像是动态的,因此具有功能。

class Adapter(DefaultAccountAdapter):

    # Redirect after succesfull login

    def get_login_redirect_url(self, request):

            return reverse('landing-dashboard')

        

    def render_mail(self, template_prefix, email, context, headers=None):

        """

        Renders an email to `email`.  `template_prefix` identifies the

        email that is to be sent, e.g. "account/email/email_confirmation"

        """

        to = [email] if isinstance(email, str) else email

        subject = render_to_string("{0}_subject.txt".format(template_prefix), context)

        # remove superfluous line breaks

        subject = " ".join(subject.splitlines()).strip()

        subject = self.format_email_subject(subject)



        from_email = self.get_from_email()



        bodies = {}

        for ext in ["html", "txt"]:

            try:

                template_name = "{0}_message.{1}".format(template_prefix, ext)

                bodies[ext] = render_to_string(

                    template_name,

                    context,

                    self.request,

                ).strip()

            except TemplateDoesNotExist:

                if ext == "txt" and not bodies:

                    # We need at least one body

                    raise

        if "txt" in bodies:

            msg = EmailMultiAlternatives(

                subject, bodies["txt"], from_email, to, headers=headers

            )

            if "html" in bodies:

                msg.attach_alternative(bodies["html"], "text/html")

                msg.attach(logo_data())

                msg.attach(background_data())

        else:

            msg = EmailMessage(subject, bodies["html"], from_email, to, headers=headers)

            msg.content_subtype = "html"  # Main content is now text/html

        return msg



    def send_mail(self, template_prefix, email, context):

        msg = self.render_mail(template_prefix, email, context)

        msg.send()