我想使用Django模板发送HTML电子邮件,如下所示:
<html>
<body>
hello <strong>{{username}}</strong>
your account activated.
<img src="mysite.com/logo.gif" />
</body>我找不到任何关于send_mail的东西,而且django-mailer只发送超文本标记语言模板,没有动态数据。
如何使用Django的模板引擎生成电子邮件?
发布于 2010-05-11 19:30:30
在the 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下的templates目录中
Hello {{ username }} - your account is activated.和一个存储在email.html下的HTMLy文件
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()发布于 2011-03-17 06:50:11
在这个解决方案的启发下,我制作了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',}这将自动查找名为'templated_email/email.txt‘和'templated_email/email.html’的模板,分别用于普通的django模板目录/加载器中的普通和html部分(如果它找不到任何一个则会报错)。
发布于 2014-01-31 10:56:18
使用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()https://stackoverflow.com/questions/2809547
复制相似问题