在 Django 中发送电子邮件的正确文件结构

Proper File Structure For Sending E-Mails In Django

我在我的 Django 视图中像这样发送很多电子邮件

if form.is_valid():
            form.save()

            # email contents
            first_name = form.cleaned_data['first_name']
            surname = form.cleaned_data['surname']
            full_name = first_name + ' ' + surname
            from_email = form.cleaned_data['email']

            try:
                html_content = """
                <p>HEADING</p>
                
                <p>Sent from: """+ full_name +""".</p>

                <p>Email address: """+ from_email +""".</p>
                """

                email = EmailMessage('TITLE', html_content, 'example@gmail.com', ['example@gmail.com'])
                email.content_subtype = "html"
                email.send()

            except BadHeaderError:
                return HttpResponse('Invalid header found.')

            return redirect('example', first_name=first_name)

但我确信在发送电子邮件时必须有一个标准的文件结构和方法来分离逻辑。

如果有,或者如果有人有任何整洁的方法来组织许多电子邮件的内容而不是让它们膨胀我的观点,请分享:)。

谢谢。

我会按照以下方式进行操作:

首先,将在我的模板文件夹中的某处创建一个 HTML 模板。

somewhere/templates/some_email.html

<p>HEADING</p>
<p>Sent from: {{ full_name }}.</p>
<p>Email address: {{ from_email }}.</p>

然后两个辅助函数,一个用于渲染,一个用于发送。

from typing import List, Tuple, Union

from django.core.mail import EmailMessage
from django.template import loader


Recipient_s = Union[List[str], Tuple[str], str]


def render_body(template_name: str, context: dict = None) -> str:
    """
    Load template by given name, pass it context
    and render as a string.
    """
    template = loader.get_template(template_name)
    return template.render(context)


def send_email(
    subject: str,
    template_name: str,
    context: dict,
    to: Recipient_s,
    bcc: Recipient_s = None,
    cc: Recipient_s = None,
    reply_to: Recipient_s = None,
):

    if not to:
        return

    body = render_body(template_name, context)

    email = EmailMessage(
        subject=subject,
        body=body,
        to=[to],
        bcc=[bcc] if bcc else None,
        cc=[cc] if cc else None,
        reply_to=[reply_to] if reply_to else None,
    )

    # Setting main content
    email.content_subtype = "html"

    email.send()

然后只需从如下视图调用该函数:

send_email(subject='BLABLABLA', template_name='some_email.html', context={'first_name': 'John', 'from_email': 'john@example.com'}...)