238

我想使用这样的 Django 模板发送 HTML 电子邮件:

<html>
<body>
hello <strong>{{username}}</strong>
your account activated.
<img src="mysite.com/logo.gif" />
</body>

我找不到任何关于的内容send_mail,并且 django-mailer 只发送 HTML 模板,没有动态数据。

如何使用 Django 的模板引擎生成电子邮件?

4

12 回答 12

420

docs中,要发送 HTML 电子邮件,您需要使用其他内容类型,如下所示:

from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

您可能需要两个电子邮件模板 - 一个看起来像这样的纯文本模板,存储在您的模板目录下email.txt

Hello {{ username }} - your account is activated.

和一个HTMLy,存储在email.html

Hello <strong>{{ username }}</strong> - your account is activated.

然后,您可以使用这两个模板发送电子邮件get_template,如下所示:

from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context

plaintext = get_template('email.txt')
htmly     = get_template('email.html')

d = Context({ 'username': username })

subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = plaintext.render(d)
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
于 2010-05-11T11:30:30.143 回答
285

由于 Django 的 1.7 在send_email方法html_message中添加了参数。

html_message:如果提供了 html_message,则生成的电子邮件将是多部分/替代电子邮件,其中 message 作为 text/plain 内容类型,html_message 作为 text/html 内容类型。

所以你可以:

from django.core.mail import send_mail
from django.template.loader import render_to_string


msg_plain = render_to_string('templates/email.txt', {'some_params': some_params})
msg_html = render_to_string('templates/email.html', {'some_params': some_params})

send_mail(
    'email title',
    msg_plain,
    'some@sender.com',
    ['some@receiver.com'],
    html_message=msg_html,
)
于 2015-02-12T11:48:18.297 回答
27

受此解决方案的启发,我制作了django-templated-email来解决这个问题(并且需要在某些时候从使用 django 模板切换到使用 mailchimp 等用于交易的模板集,模板化电子邮件我自己的项目)。虽然它仍然是一个正在进行中的工作,但对于上面的示例,您将执行以下操作:

from templated_email import send_templated_mail
send_templated_mail(
        'email',
        'from@example.com',
        ['to@example.com'],
        { 'username':username }
    )

在 settings.py 中添加以下内容(以完成示例):

TEMPLATED_EMAIL_DJANGO_SUBJECTS = {'email':'hello',}

这将在普通的 django 模板目录/加载器中分别为普通和 html 部分自动查找名为“templated_email/email.txt”和“templated_email/email.html”的模板(抱怨它是否找不到其中至少一个) .

于 2011-03-16T22:50:11.200 回答
16

我知道这是一个老问题,但我也知道有些人就像我一样,总是在寻找最新的答案,因为如果不更新旧答案有时可能包含不推荐使用的信息。

现在是 2020 年 1 月,我正在使用 Django 2.2.6 和 Python 3.7

注意:我使用DJANGO REST FRAMEWORK,下面用于发送电子邮件的代码位于我的模型视图集中views.py

因此,在阅读了多个不错的答案之后,这就是我所做的。

from django.template.loader import render_to_string
from django.core.mail import EmailMultiAlternatives

def send_receipt_to_email(self, request):

    emailSubject = "Subject"
    emailOfSender = "email@domain.com"
    emailOfRecipient = 'xyz@domain.com'

    context = ({"name": "Gilbert"}) #Note I used a normal tuple instead of  Context({"username": "Gilbert"}) because Context is deprecated. When I used Context, I got an error > TypeError: context must be a dict rather than Context

    text_content = render_to_string('receipt_email.txt', context, request=request)
    html_content = render_to_string('receipt_email.html', context, request=request)

    try:
        #I used EmailMultiAlternatives because I wanted to send both text and html
        emailMessage = EmailMultiAlternatives(subject=emailSubject, body=text_content, from_email=emailOfSender, to=[emailOfRecipient,], reply_to=[emailOfSender,])
        emailMessage.attach_alternative(html_content, "text/html")
        emailMessage.send(fail_silently=False)

    except SMTPException as e:
        print('There was an error sending an email: ', e) 
        error = {'message': ",".join(e.args) if len(e.args) > 0 else 'Unknown Error'}
        raise serializers.ValidationError(error)

重要的!那么如何render_to_string得到receipt_email.txtreceipt_email.html?在我的settings.py,我有TEMPLATES,下面是它的外观

注意DIRS,有这条线os.path.join(BASE_DIR, 'templates', 'email_templates') 。这条线使我的模板可以访问。在我的 project_dir 中,我有一个名为 的文件夹templates和一个名为email_templatesthis的子目录project_dir->templates->email_templates。我的模板在sub_directoryreceipt_email.txt下。receipt_email.htmlemail_templates

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'templates', 'email_templates')],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},
]

让我补充一下,我的recept_email.txt长相是这样的;

Dear {{name}},
Here is the text version of the email from template

而且,我的receipt_email.html长相是这样的;

Dear {{name}},
<h1>Now here is the html version of the email from the template</h1>
于 2020-01-06T20:36:15.257 回答
15

使用 EmailMultiAlternatives 和 render_to_string 来使用两个替代模板(一个是纯文本模板,一个是 html 模板):

from django.core.mail import EmailMultiAlternatives
from django.template import Context
from django.template.loader import render_to_string

c = Context({'username': username})    
text_content = render_to_string('mail/email.txt', c)
html_content = render_to_string('mail/email.html', c)

email = EmailMultiAlternatives('Subject', text_content)
email.attach_alternative(html_content, "text/html")
email.to = ['to@example.com']
email.send()
于 2014-01-31T02:56:17.693 回答
6

我创建了Django Simple Mail,以便为您要发送的每封交易电子邮件提供一个简单、可定制且可重用的模板。

电子邮件内容和模板可以直接从 django 的管理员中编辑。

使用您的示例,您将注册您的电子邮件:

from simple_mail.mailer import BaseSimpleMail, simple_mailer


class WelcomeMail(BaseSimpleMail):
    email_key = 'welcome'

    def set_context(self, user_id, welcome_link):
        user = User.objects.get(id=user_id)
        return {
            'user': user,
            'welcome_link': welcome_link
        }


simple_mailer.register(WelcomeMail)

并以这种方式发送:

welcome_mail = WelcomeMail()
welcome_mail.set_context(user_id, welcome_link)
welcome_mail.send(to, from_email=None, bcc=[], connection=None, attachments=[],
                   headers={}, cc=[], reply_to=[], fail_silently=False)

我很想得到任何反馈。

于 2018-08-10T14:12:44.967 回答
3

Django Mail Templated是一个功能丰富的 Django 应用程序,用于使用 Django 模板系统发送电子邮件。

安装:

pip install django-mail-templated

配置:

INSTALLED_APPS = (
    ...
    'mail_templated'
)

模板:

{% block subject %}
Hello {{ user.name }}
{% endblock %}

{% block body %}
{{ user.name }}, this is the plain text part.
{% endblock %}

Python:

from mail_templated import send_mail
send_mail('email/hello.tpl', {'user': user}, from_email, [user.email])

更多信息:https ://github.com/artemrizhov/django-mail-templated

于 2012-10-05T13:56:44.210 回答
3

示例中有错误....如果按照写的方式使用,会出现如下错误:

< type 'exceptions.Exception' >: 'dict' 对象没有属性 'render_context'

您将需要添加以下导入:

from django.template import Context

并将字典更改为:

d = Context({ 'username': username })

请参阅http://docs.djangoproject.com/en/1.2/ref/templates/api/#rendering-a-context

于 2011-01-03T19:10:33.893 回答
3

send_emai()对我不起作用,所以我EmailMessage 在 django docs 中使用。

我已经包含了两个版本的分析器:

  1. 仅使用 html 电子邮件版本
  2. 带有纯文本电子邮件和 html 电子邮件版本
from django.template.loader import render_to_string 
from django.core.mail import EmailMessage

# import file with html content
html_version = 'path/to/html_version.html'

html_message = render_to_string(html_version, { 'context': context, })

message = EmailMessage(subject, html_message, from_email, [to_email])
message.content_subtype = 'html' # this is required because there is no plain text email version
message.send()

如果您想包含电子邮件的纯文本版本,请像这样修改上面的内容:

from django.template.loader import render_to_string 
from django.core.mail import EmailMultiAlternatives # <= EmailMultiAlternatives instead of EmailMessage

plain_version = 'path/to/plain_version.html' # import plain version. No html content
html_version = 'path/to/html_version.html' # import html version. Has html content

plain_message = render_to_string(plain_version, { 'context': context, })
html_message = render_to_string(html_version, { 'context': context, })

message = EmailMultiAlternatives(subject, plain_message, from_email, [to_email])
message.attach_alternative(html_message, "text/html") # attach html version
message.send()

我的普通版和 html 版如下所示:plain_version.html:

Plain text {{ context }}

html_version.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 ...
 </head>
<body>
<table align="center" border="0" cellpadding="0" cellspacing="0" width="320" style="border: none; border-collapse: collapse; font-family:  Arial, sans-serif; font-size: 14px; line-height: 1.5;">
...
{{ context }}
...
</table>
</body>
</html>
于 2020-06-25T19:25:02.953 回答
0

如果您想要邮件的动态电子邮件模板,请将电子邮件内容保存在数据库表中。这是我在数据库中保存为 HTML 代码的内容 =

<p>Hello.. {{ first_name }} {{ last_name }}.  <br> This is an <strong>important</strong> {{ message }}
<br> <b> By Admin.</b>

 <p style='color:red'> Good Day </p>

在您看来:

from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template

def dynamic_email(request):
    application_obj = AppDetails.objects.get(id=1)
    subject = 'First Interview Call'
    email = request.user.email
    to_email = application_obj.email
    message = application_obj.message

    text_content = 'This is an important message.'
    d = {'first_name': application_obj.first_name,'message':message}
    htmly = FirstInterviewCall.objects.get(id=1).html_content #this is what i have saved previously in database which i have to send as Email template as mentioned above HTML code

    open("partner/templates/first_interview.html", "w").close() # this is the path of my file partner is the app, Here i am clearing the file content. If file not found it will create one on given path.
    text_file = open("partner/templates/first_interview.html", "w") # opening my file
    text_file.write(htmly) #putting HTML content in file which i saved in DB
    text_file.close() #file close

    htmly = get_template('first_interview.html')
    html_content = htmly.render(d)  
    msg = EmailMultiAlternatives(subject, text_content, email, [to_email])
    msg.attach_alternative(html_content, "text/html")
    msg.send()

这将发送您保存在 Db 中的动态 HTML 模板。

于 2018-07-26T04:29:54.340 回答
0

我写了一个片段,允许您发送使用存储在数据库中的模板呈现的电子邮件。一个例子:

EmailTemplate.send('expense_notification_to_admin', {
    # context object that email template will be rendered with
    'expense': expense_request,
})
于 2018-02-17T12:03:31.410 回答
0

我喜欢使用这个工具来允许通过简单的上下文处理轻松发送电子邮件 HTML 和 TXT:https ://github.com/divio/django-emailit

于 2017-04-20T15:35:42.227 回答