通过django发送专业电子邮件

时间:2017-01-31 11:33:45

标签: django email

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()

我希望能够发送已正确设计的简报或电子邮件,如果可能,还包括图片。我想知道我是否可以改变这个

html_content = '<p>This is an <strong>important</strong> message.</p>'

进入html模板文件。喜欢这个

html_content = 'newsletter/news.html'

如果没有,那么如何发送Quora和其他网站的电子邮件。

2 个答案:

答案 0 :(得分:2)

您可以轻松地将任何模板转换为字符串,用于任何目的,包括发送邮件:

from django.template.loader import get_template

template = get_template('newsletter/news.html')
html_content = template.render({pass any context you might need})

答案 1 :(得分:2)

您不能直接传递这样的模板,但可以使用render_to_string

from django.template.loader import render_to_string
html_content  = render_to_string('newsletter/news.html', {'foo': 'bar'})

但请注意,HTML电子邮件存在某些限制。例如,您不能使用javascript。可能会显示图像,也可能不会显示图像,也不能使用外部样式表。

相关问题