Skip to content

Mail

hypha.core.mail

logger module-attribute

logger = getLogger(__name__)

MarkdownMail

MarkdownMail(template_name)

Bases: object

Render and send an html + plain-text email using a markdown template.

Usages:

email = MarkdownMail("messages/email/send_reset_email.md") email.send(to='xyz@email.com', from=settings.DEFAULT_FROM_EMAIL, context={'key': 'value'})

Translates the email based on Django settings or 'lang' parameter available in the context.

Adds Auto-Submitted header.

Source code in hypha/core/mail.py
def __init__(self, template_name: str):
    self._email = None

    if template_name is not None:
        self.template_name = template_name

template_name class-attribute instance-attribute

template_name = ''

make_email_object

make_email_object(to, context, **kwargs)
Source code in hypha/core/mail.py
def make_email_object(self, to: str | List[str], context, **kwargs):
    if not isinstance(to, (list, tuple)):
        to = [to]

    lang = context.get("lang", None) or settings.LANGUAGE_CODE

    with language(lang):
        rendered_template = self._render_template(context)
        body_txt = remove_extra_empty_lines(rendered_template)
        body_html = markdown_to_html(rendered_template)

    email = EmailMultiAlternatives(**kwargs)
    email.body = body_txt
    email.attach_alternative(body_html, "text/html")

    email.to = to

    return email

send

send(to, context, **kwargs)
Source code in hypha/core/mail.py
def send(self, to: str | List[str], context, **kwargs):
    kwargs.setdefault("headers", {})
    kwargs["headers"].update({"Auto-Submitted": "auto-generated"})

    email = self.make_email_object(to, context, **kwargs)
    return email.send()

remove_extra_empty_lines

remove_extra_empty_lines(text)

Removes extra blank lines and spaces from markdown generated using Django templates. Do this for readably of markdown itself.

Source code in hypha/core/mail.py
def remove_extra_empty_lines(text: str) -> str:
    """Removes extra blank lines and spaces from markdown generated
    using Django templates. Do this for readably of markdown itself.
    """
    return re.sub(r"\n\s*\n", "\n\r", text)

language

language(lang)
Source code in hypha/core/mail.py
@contextmanager
def language(lang):
    old_language = translation.get_language()
    try:
        translation.activate(lang)
        yield
    finally:
        translation.activate(old_language)