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()
<p>Hello.. {{ first_name }} {{ last_name }}. <br> This is an <strong>important</strong> {{ message }}
<br> <b> By Admin.</b>
<p style='color:red'> Good Day </p>
在您的观点中:
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
def dynamic_email(request):
application_obj = AppDetails.objects.get(id=1)
subject = 'First Interview Call'
email = request.user.email
to_email = application_obj.email
message = application_obj.message
text_content = 'This is an important message.'
d = {'first_name': application_obj.first_name,'message':message}
htmly = FirstInterviewCall.objects.get(id=1).html_content #this is what i have saved previously in database which i have to send as Email template as mentioned above HTML code
open("partner/templates/first_interview.html", "w").close() # this is the path of my file partner is the app, Here i am clearing the file content. If file not found it will create one on given path.
text_file = open("partner/templates/first_interview.html", "w") # opening my file
text_file.write(htmly) #putting HTML content in file which i saved in DB
text_file.close() #file close
htmly = get_template('first_interview.html')
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, text_content, email, [to_email])
msg.attach_alternative(html_content, "text/html")
msg.send()
10 回答
我喜欢使用这个工具,允许轻松发送电子邮件HTML和TXT,方便上下文处理:https://github.com/divio/django-emailit
我写了一个snippet,它允许您发送使用存储在数据库中的模板呈现的电子邮件 . 一个例子:
我创建了Django Simple Mail,为您要发送的每封交易电子邮件都提供了一个简单,可自定义且可重复使用的模板 .
电子邮件内容和模板可以直接从django的管理员编辑 .
在您的示例中,您将注册您的电子邮件:
并以这种方式发送:
我很想得到任何反馈 .
男孩和女孩!
由于Django在send_email方法中的1.7,因此添加了
html_message
参数 .所以你可以:
使用EmailMultiAlternatives和render_to_string来使用两个替代模板(一个是纯文本,一个是html):
我已经做了django-templated-email以努力解决这个问题,受到这个解决方案的启发(并且需要在某些时候从使用django模板转换为使用mailchimp等模板为我自己的项目的事务性,模板化电子邮件设置) . 尽管如此,它仍然是一项正在进行中的工作,但对于上面的示例,您将执行以下操作:
通过在settings.py中添加以下内容(以完成示例):
这将分别在普通的django模板目录/加载器中自动查找名为“templated_email / email.txt”和“templated_email / email.html”的模板,用于普通django模板dirs / loaders(抱怨如果找不到其中的至少一个) .
Django Mail Templated 是一个功能丰富的Django应用程序,用于发送带有Django模板系统的电子邮件 .
安装:
组态:
模板:
蟒蛇:
更多信息:https://github.com/artemrizhov/django-mail-templated
示例中存在错误....如果您按写入方式使用它,则会发生以下错误:
您需要添加以下导入:
并将字典更改为:
见http://docs.djangoproject.com/en/1.2/ref/templates/api/#rendering-a-context
从the docs开始,要发送HTML电子邮件,您要使用其他内容类型,如下所示:
您可能需要两个用于电子邮件的模板 - 一个看起来像这样的纯文本模板,存储在
email.txt
下的模板目录中:和一个HTMLy,存储在
email.html
下:然后,您可以使用get_template使用这两个模板发送电子邮件,如下所示:
如果您想要邮件的动态电子邮件模板,请将电子邮件内容保存在数据库表中 . 这就是我在database =中保存为HTML代码的内容
在您的观点中:
这将发送您在Db中保存的动态HTML模板 .