Django纯文本电子邮件模板在模板标记之后生成\n

2024-05-07 20:13:23 发布

您现在位置:Python中文网/ 问答频道 /正文

这里有一个有趣的问题:我的Django应用程序发送了纯文本电子邮件,代码如下:

email_context = dict()
email_context['to'] = user.display_name
email_context['new'] = user_data['new']
email_context['for_reminder'] = user_data['for_reminder']

plaintext = get_template('email/notification.txt')
text_content = plaintext.render_to_string(email_context)

html = get_template('email/notification.html')
html_content = html.render(email_context)

email = EmailMultiAlternatives(
    subject='Assignments',
    body=text_content,
    to=[user.email],
    reply_to=[settings.DEFAULT_FROM_EMAIL],
)

# email.attach_alternative(html_content, "text/html")

email.send()  

“email/notification_base.txt”模板如下所示:

Dear {{ to }},
{% if new %}
You have been assigned to the following NEW cases:
{% block new %}
{% endblock %}
{% endif %}
{% if for_reminder %}
You still have the following previously assigned cases, which need your attention:
{% block for_reminder %}
{% endblock %}
{% endif %}
Thank you for your assistance.

Sincerely,
The Team

“email/notification.txt”模板只是扩展了基础:

{% extends 'email/notification_base.txt' %}

{% load common_tags %}
{% load common_filters %}

{% block new %}
{% for dispute in new %}
Case #: {{ dispute.case_id.no}}
Assignment date: {{ dispute.assignment_date }}
{% endfor %}
{% endblock %}

{% block for_reminder %}
{% for dispute in for_reminder %}
Case #: {{ dispute.case_id.no }}
Assignment date: {{ dispute.assignment_date }}
{% endfor %}
{% endblock %}

我的问题是,它生成并发送给收件人的电子邮件实际上在模板有{%something%}标记的每个位置都有一个换行符。这导致电子邮件文本的格式非常不均匀。例如,如果两个块都丢失,则电子邮件将如下所示:

Dear Someone,



Thank you for your assistance.

Sincerely,
The Team

有没有办法解决这个问题


Tags: totxtnewfor电子邮件emailhtmlcontext