Exemplo n.º 1
0
def send_mail(
    subject: str,
    html_body: str,
    from_email: str,
    to: List[str],
    categories: List[str] = None,
    reply_to: str = None,
    headers: dict = None,
    preheader: str = None,
    template_id: str = None,
):
    """Send mail using the dynamic template specified by template_id.

    This template should include these variables:
    - Subject: {{ subject }}
    - Preheader: {{ preheader }}
    - Somewhere in the template: {{{ body }}}

    Tip: to display a name for the from_email, use this format:
    - `"Name" <*****@*****.**>`
    """
    if headers is None:
        headers = dict()
    headers["Reply-To"] = reply_to

    raw_body = strip_tags(html_body)
    mail = EmailMultiAlternatives(subject=subject,
                                  body=raw_body,
                                  from_email=from_email,
                                  to=to,
                                  headers=headers)
    if not template_id:
        template_id = settings.TEMPLATE_ID

    mail.template_id = template_id
    mail.dynamic_template_data = dict(body=html_body,
                                      subject=subject,
                                      preheader=preheader)
    if categories:
        mail.categories = categories

    mail.send()
    def render_mail(self, template_prefix, email, context):
        """
            Renders an e-mail to `email`.  `template_prefix` identifies the
            e-mail that is to be sent, e.g. "account/email/email_confirmation"
            """
        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).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, [email])
            if "html" in bodies:
                msg.attach_alternative(bodies["html"], "text/html")
                html_body = bodies["html"]
            else:
                html_body = linebreaksbr(bodies["txt"])
        else:
            msg = EmailMessage(subject, bodies["html"], from_email, [email])
            msg.content_subtype = "html"  # Main content is now text/html
            body = bodies["html"]

        msg.template_id = settings.TEMPLATE_ID
        msg.dynamic_template_data = dict(body=html_body, subject=subject)
        return msg