Login

Using Templates to Send E-Mails

Author:
rpoulton
Posted:
March 1, 2007
Language:
Python
Version:
Pre .96
Score:
5 (after 5 ratings)

This is a basic example for sending an email to a user (in this case, when they've signed up at a website) using the Django template framework.

It's really quite simple - we're just using a plain text template instead of HTML, and using the output of the template's 'render()' method as the message body.

Of course, in your project you won't blindly use data from request.POST!

This example was first posted on my blog at rossp.org

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from django.template import loader, Context
from django.core.mail import send_mail

t = loader.get_template('registration/email.txt')
c = Context({
    'name': request.POST.get('name'),
    'username': request.POST.get('username'),
    'product_name': 'Your Product Name',
    'product_url': 'http://www.yourproject.com/',
    'login_url': 'http://www.yourproject.com/login/',
})


send_mail('Welcome to My Project', t.render(c), '[email protected]', ['[email protected]',], fail_silently=False)

##############################################################
Sample Template for the above: registration/email.txt
##############################################################
Dear {{ name }},

Thank you for signing up with {{ product_name }}.

Your new username is {{ username }}, and you can login at {{ login_url }}. Once logged in, you'll be able to access more features on our website..

We hope that {{ product_name }} is of good use to you. If you have any feedback, please respond to this e-mail or submit it to us via our website.

Regards,

{{ product_name }} Administration
{{ product_url }}

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

djanphil (on July 15, 2007):

How do I separate the logic from the template? Where do I place the logic (in a python script, a view, or what?)

#

rpoulton (on October 3, 2007):

Just saw this comment, apologies for the late response.

Lines 1-14 would be in your view, whilst lines 19-30 are in a template called 'registration/email.txt'.

#

ubernostrum (on October 19, 2007):

The function render_to_string in django.template.loader would make this quite a bit shorter; it's somewhat like render_to_response except it returns the rendered string from the template instead of an HttpResponse.

#

Please login first before commenting.