Sending email with html in Django 1.7

2020-06-27 01:25发布

问题:

In send_mail() we have one new parameter - html_message. Docs

I have email.html file and I want to send html version of my message. I can't find any example for Django 1.7.

Can you show me a way, how to do this? Does I need to use os.open() my html file?

Thanks!

回答1:

render_to_string : which loads a template, renders it and returns the resulting string. html_message : If html_message is provided, the default message replaced with Html message.

mail/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)


回答2:

Tim,

You don't need OS.open. You can do this by creating an html template first, and importing it using the get_template method. In your view, add something along the lines of :

app/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()

Note: You don't need Context for Djange 1.10+. In Django 1.8+, the template's render method takes a dictionary for the context parameter. Support for passing a Context instance is deprecated, and gives an error in Django 1.10+.