Django send email on localhost and using Template for content


The most common things while developing django application is sending email. Django have built-in function for sending email called “send_email” under django.core.mail. When we using long text of emails content and testing in our local, then we need to set it working on localhost and templating.

1. Set up django send email on local
We can print email on console by edit this settings.py part:

1
EMAIL_BACKEND = ‘django.core.mail.backends.console.EmailBackend’

When you executing “send_email” in python manage.py shell, you will see the result in console. Eg:

1
send_mail("hello", "world", "support@yodi.sg", ["yodi@yodi.sg"])

Will showing results:

1
2
3
4
5
6
7
8
9
10
11
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: quoted-printable
Subject: hello
From: support@yodi.sg
To: yodi@yodi.sg
Date: Fri, 02 Nov 2012 02:39:55 -0000
Message-ID: <20121102023955.29091.62317@trip>

world
——————————————————

Then, the last step we need to know is using template for sending emails. We need to use loader and Context from django.template. All we need just render content and put it inside send_mail.

eg:

1
2
3
4
5
6
7
t = loader.get_template("users/emails/data.txt")
c = Context({
             "data": data,
             })
# Send Email to Traveler
send_mail("Your payments in Tripvillas.com", t.render(c),
          ‘support@tripvillas.com’, [instance.traveler.email])

# Updated version – Thanks to my Swedish friends @kitsunde:

1
2
3
4
5
6
from django.template.loader import render_to_string
rendered = render_to_string("users/emails/data.txt", {‘data’: data})

# Send Email to Traveler
send_mail("Your payments in Tripvillas.com", rendered,
          ‘support@tripvillas.com’, [instance.traveler.email])

And data.txt contain your templates, eg:

1
Hello world! {{ data }}

Now you can use template and test email in your local on same time 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.