如何发送带有动态内容的django的HTML电子邮件? [英] How to send html email with django with dynamic content in it?

查看:132
本文介绍了如何发送带有动态内容的django的HTML电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能帮助我发送包含动态内容的html电子邮件。一种方法是将整个html代码复制到一个变量中,并在Django视图中填充其中的动态代码,但这似乎不是一个好主意,因为它的HTML文件非常大。

Can anyone please help me sending html email with dynamic contents. One way is to copy the entire html code into a variable and populate the dynamic code within it in Django views, but that does not seem to be a good idea, as its a very large html file.

我将不胜感激。

谢谢。

推荐答案

Django包括了 django.core.mail.send_mail 方法,天(2018年),无需直接使用 EmailMultiAlternatives 类。改为执行以下操作:

Django includes the django.core.mail.send_mail method these days (2018), no need to use EmailMultiAlternatives class directly. Do this instead:

from django.core import mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags

subject = 'Subject'
html_message = render_to_string('mail_template.html', {'context': 'values'})
plain_message = strip_tags(html_message)
from_email = 'From <from@example.com>'
to = 'to@example.com'

mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)

这将发送一封电子邮件,具有html功能的浏览器,并将在残缺的电子邮件查看器中显示纯文本。

This will send an email which is visible in both html-capable browsers and will show plain text in crippled email viewers.

这篇关于如何发送带有动态内容的django的HTML电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆