views:

465

answers:

2

hey,

i wanna send emails in html template like this.

<html>
<body>
hello <strong>{{username}}</strong>
your account activated.
<img src="mysite.com/logo.gif" />
</body>

it means, i want to send fully html powered templates, with django datas. i cant find anything about send_mail, and django-mailer only sends html templates, not with dynamic datas?

any idea about html emails ?

thanks.

A: 

Render the email body yourself first.

Ignacio Vazquez-Abrams
+5  A: 

From the docs, to send HTML e-mail you want to use alternative content-types, like this:

from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', '[email protected]', '[email protected]'
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()

You'll probably want two templates for your e-mail - a plain text one that looks something like this, stored in your templates directory under email.txt:

Hello {{ username }} - your account is activated.

and an HTMLy one, stored under email.html:

Hello <strong>{{ username }}</strong> - your account is activated.

You can then send an e-mail using both those templates by making use of get_template, like this:

from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template

plaintext = get_template('email.txt')
htmly     = get_template('email.html')

d = { 'username': username }

subject, from_email, to = 'hello', '[email protected]', '[email protected]'
text_content = plaintext.render(d)
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
Dominic Rodger