使用Django创建电子邮件模板

Ana*_*kin 193 email django django-mailer django-email

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

<html>
<body>
hello <strong>{{username}}</strong>
your account activated.
<img src="mysite.com/logo.gif" />
</body>
Run Code Online (Sandbox Code Playgroud)

我找不到任何东西send_mail,django-mailer只发送HTML模板,没有动态数据.

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

Dom*_*ger 363

文档中,要发送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()
Run Code Online (Sandbox Code Playgroud)

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

Hello {{ username }} - your account is activated.
Run Code Online (Sandbox Code Playgroud)

和一个HTMLy,存储在email.html:

Hello <strong>{{ username }}</strong> - your account is activated.
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用这两个模板发送电子邮件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()
Run Code Online (Sandbox Code Playgroud)

  • 我想你可以用[render_to_string](https://docs.djangoproject.com/en/dev/ref/templates/api/#the-render-to-string-shortcut)简化这个,这会让你失去一个单独的将模板分配给`plaintext`和`htmly`,并在定义`text_content`和`html_content`时设置模板和上下文. (39认同)
  • 这个答案应该是Django手册的一部分! (11认同)
  • @Hafnernuss 答案适用于 2021 年的 Django `3.1.5` 和 python `3.8.5`。不需要“from django.template import Context”。只需执行 `d = { 'username': username }` 即可。 (6认同)
  • @akki在下面看到了andi的答案,这也简化了替代部分,这要归功于在Django 1.7中将send_email()中的html_message param添加到了 (3认同)
  • 感谢您的有用回答。如今,上下文应该只是一个命令。因此,正确的方法不是 d = Context({...}),而是 d = {...} ;) (2认同)

and*_*abs 220

男孩和女孩!

由于Django在send_email方法中的1.7,html_message因此添加了参数.

html_message:如果提供了html_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,
)
Run Code Online (Sandbox Code Playgroud)

  • 那应该被认为是正确的答案。 (5认同)
  • 请注意,如果 'email.txt' 和 'email.html' 位于设置中定义的目录模板中,而不仅仅是 render_to_string('email.txt', {'some_params': some_params}_ (2认同)
  • 需要从文件名中删除“templates”(至少在 python 3.8 中),否则会产生“django.template.exceptions.TemplateDoesNotExist”错误。默认路径是相对于模板文件夹的 (2认同)

Dar*_*arb 25

我已经制作了django-templated-email以努力解决这个问题,受到这个解决方案的启发(并且需要在某些时候从使用django模板切换到使用mailchimp等模板来处理事务性,模板化的电子邮件我自己的项目).尽管如此,它仍然是一项正在进行的工作,但对于上面的示例,您可以这样做:

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

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

TEMPLATED_EMAIL_DJANGO_SUBJECTS = {'email':'hello',}
Run Code Online (Sandbox Code Playgroud)

这将分别在普通的django模板目录/加载器中自动查找名为"templated_email/email.txt"和"templated_email/email.html"的模板,用于普通django模板dirs/loaders(抱怨如果找不到其中的至少一个) .


Ric*_*era 14

使用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()
Run Code Online (Sandbox Code Playgroud)


man*_*kin 14

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

现在是 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)
Run Code Online (Sandbox Code Playgroud)

重要的!那么render_to_stringgetreceipt_email.txtreceipt_email.html呢?在我的settings.py, 我有TEMPLATES,下面是它的样子

注意DIRS,有这一行os.path.join(BASE_DIR, 'templates', 'email_templates') 。这一行使我的模板可访问。在我的 project_dir 中,我有一个名为 的文件夹templates,以及一个名为email_templatesthis的 sub_directory project_dir->templates->email_templates。我的模板receipt_email.txtreceipt_email.htmlemail_templatessub_directory 下。

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',
        ],
    },
},
]
Run Code Online (Sandbox Code Playgroud)

让我补充一点,我的recept_email.txt样子是这样的;

Dear {{name}},
Here is the text version of the email from template
Run Code Online (Sandbox Code Playgroud)

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

Dear {{name}},
<h1>Now here is the html version of the email from the template</h1>
Run Code Online (Sandbox Code Playgroud)


Cha*_*thk 5

我创建了Django简单邮件,为您要发送的每个交易电子邮件提供了一个简单,可自定义和可重用的模板。

电子邮件内容和模板可以直接从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)
Run Code Online (Sandbox Code Playgroud)

并以这种方式发送:

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)
Run Code Online (Sandbox Code Playgroud)

我希望得到任何反馈。