Python 在Django 1.7中使用html发送电子邮件
在send\u mail()中,我们有一个新参数-Python 在Django 1.7中使用html发送电子邮件,python,html,django,email,Python,Html,Django,Email,在send\u mail()中,我们有一个新参数-html\u message 我有email.html文件,我想发送邮件的html版本。我找不到Django 1.7的任何示例 你能告诉我怎么做吗?我是否需要使用os.open()我的html文件 谢谢 render\u to\u string:加载模板,呈现它并返回结果string。 html\u消息:如果提供了html\u消息,则默认消息将替换为html消息 mail/html message.html Hi {{ first_name }}
html\u message
我有email.html文件,我想发送邮件的html版本。我找不到Django 1.7的任何示例
你能告诉我怎么做吗?我是否需要使用os.open()我的html文件
谢谢
render\u to\u string
:加载模板,呈现它并返回结果string
。
html\u消息
:如果提供了html\u消息
,则默认消息将替换为html消息
mail/html message.html
Hi {{ first_name }}.
This is your {{ email }}
Thank you
视图.py
def mail_function(request):
subject = 'Test Mail'
from = 'info@domain.com'
to = 'to@domain.com'
c = Context({'email': email,
'first_name': first_name})
html_content = render_to_string('mail/html-message.html', c)
txtmes = render_to_string('mail/text-message.html', c)
send_mail(subject,
txtmes,
from,
[to],
fail_silently=False,
html_message=html_content)
from django.core.mail import EmailMultiAlternatives
from django.http import HttpResponse
from django.template.loader import get_template
def send_mail(request):
text = get_template('email_template.txt')
html = get_template('email_template.html')
data = {'templating variable': data_var}
# If Client cant receive html mails, it will receive the text
# only version.
# Render the template with the data
content_txt = text.render(data)
content_html = html.render(data)
# Send mail
msg = EmailMultiAlternatives(subject, content_text, from_email, [to])
msg.attach_alternative(content_html, "text/html")
msg.send()
蒂姆
你不需要操作系统打开。您可以先创建一个html模板,然后使用get_template方法导入它。在你的
查看、添加以下内容:
app/view.py
def mail_function(request):
subject = 'Test Mail'
from = 'info@domain.com'
to = 'to@domain.com'
c = Context({'email': email,
'first_name': first_name})
html_content = render_to_string('mail/html-message.html', c)
txtmes = render_to_string('mail/text-message.html', c)
send_mail(subject,
txtmes,
from,
[to],
fail_silently=False,
html_message=html_content)
from django.core.mail import EmailMultiAlternatives
from django.http import HttpResponse
from django.template.loader import get_template
def send_mail(request):
text = get_template('email_template.txt')
html = get_template('email_template.html')
data = {'templating variable': data_var}
# If Client cant receive html mails, it will receive the text
# only version.
# Render the template with the data
content_txt = text.render(data)
content_html = html.render(data)
# Send mail
msg = EmailMultiAlternatives(subject, content_text, from_email, [to])
msg.attach_alternative(content_html, "text/html")
msg.send()
注意:Djange 1.10+不需要上下文。在Django 1.8+中,模板的render方法使用字典作为上下文参数。不推荐使用传递上下文实例的支持,Django 1.10+中出现错误。Django 1.10+中不推荐使用上下文。请使用普通字典而不是上下文。我需要我的模板具有动态字段,以便指定发送此邮件的人。你能用html更新答案吗。