Sending Template Based Emails from Django

Categories Django, Python

Sending Emails from Django is quick and easy. In this post I will show a basic setup for sending Emails from Django using Email templates. Using templates give us the advantage of using one Email template to send Emails to different users with different data.

First we ned to setup a SMTP server locally for development environment. There are many ways to setup SMTP server for development environments.

One of them is to use Python’s build-in way to start a “dumb” SMTP server. Run this command in terminal to start python SMTP server on local environment:

python -m smtpd -n -c DebuggingServer localhost:25

This will show Emails in terminal itself. There are other SMTP servers available with UI also. The one I user is MailSlurper. This runs locally and has browser based UI.

We need to define SMTP host and port in Django projects’s settings.py:

SERVER_EMAIL = 'root@localhost'
EMAIL_HOST = 'localhost'
EMAIL_PORT = '25'
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''

Create a directory for Email templates in you project, let’s say template. Add this directory to TEMPLATES setting of Django project’s settings.py.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Create a template for subject email_subject.html with content as template for subject. Don’t use new lines in subject template. Add {{ subject }} to contents of email_subject.html file.

Create template for body of email named email_body.html. Add following content to this template:

Hi {{ name }},

This is a demo for sending emails from django using email templates.<br/>

Thanks,
{{ sender }}

In Django view import settings, loader and send_mail:

from django.template import loader
from django.core.mail import send_mail
from MailProject import settings

To send Email in Django view’s function, we will first get and parse Email templates and then send the Email:

def send_email(request):
	# Data for parsing email templates
	context_data = {
		'subject': 'Sent from django',
		'name': 'Harshveer Singh',
		'sender': 'Django Server'
	}

	# Get Subject template
	subject_t = loader.get_template('email_subject.html')
	# Parse Subject template
	subject = subject_t.render(context_data)
	# Get Body template
	body_t = loader.get_template('email_body.html')
	# Parse Body template
	body = body_t.render(context_data)
	
	try:
		# Send mail
		send_mail(subject, body, settings.SERVER_EMAIL, ['harshveer1889@gmail.com'], fail_silently=False,)
	except:
		return HttpResponse("Failed to send email.")

	return HttpResponse("Email sent successfully.")

Now, if we call this method, it will send the Email and we can see this message in MailSlurper.

That’s all about sending Emails in Django using Templates. You can find complete project code for this on GitHub.

If you liked the post or have any suggestions, leave a comment 🙂

1 Comment

  • packagers
    February 9, 2018

    Woah! I’m reaⅼly loving the template/theme of this site.
    It’s simple, yet effective. A lot of times it’s һard to get that “perfect balance” between usability and visual appeal.
    I must say that you’ve done a amazing job with this. In addition, the blog
    loads extremely fast for me on Ӏnternet explorer.
    Excellent Blog!

Leave a Reply

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