【问题标题】:Sending professional emails through django通过 django 发送专业电子邮件
【发布时间】:2017-06-16 19:50:39
【问题描述】:
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 和其他网站的电子邮件。`

【问题讨论】:

标签: django email


【解决方案1】:

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

from django.template.loader import get_template

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 忘记了 render_to_string,它节省了一行。
    • 但是你比我早了 5 秒 @RemcoGerlich 所以这是我的 +1
    • 非常感谢...我试过了,它也有效 html_content = get_template('newsletter/news.html').render()
    猜你喜欢
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 2012-07-20
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    相关资源
    最近更新 更多