[英]Sending email with html in Django 1.7
在send_mail()中,我們有一個新參數html_message
。 文件
我有email.html文件,我想發送郵件的html版本。 我找不到Django 1.7的任何示例。
您能告訴我一種方法,該怎么做嗎? 我是否需要使用os.open()我的html文件?
謝謝!
render_to_string
:加載模板,渲染模板並返回結果string
。 html_message
:如果提供了html_message
,則默認消息將替換為Html消息。
郵件/ HTML的message.html
Hi {{ first_name }}.
This is your {{ email }}
Thank you
views.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)
蒂姆
你不需要OS.open。 您可以先創建一個html模板,然后使用get_template方法導入它。 在您看來,添加以下內容:
應用程序/ view.py
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方法采用一個context參數字典。 不推薦支持傳遞Context實例,並在Django 1.10+中出錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.