2 min read

Django shorts: #3 Sending emails

Django shorts: #3 Sending emails
Photo by Christopher Gower / Unsplash

Preface

Django is such a diverse and intricate back-end web framework, that we can utilize it to do a great many things. One of these great things is to use it to send emails.

Step 1:

First of all you need to import the following at the top of your views.py file:

from django.core.mail import send_mail 

This will allow you to make use of the send_mail function that is already imported with Django. Luckily, this comes built in with Django, so we don't need to worry about installing any packages with pip.

Step 2:

Next you need to simply create a normal view, such as mine below:


def email_invoice(request)
   
    return render(request, 'email-invoice.html')

Step 3:

In the next step, you will need to make use of the send_mail function in your chose view like so:

def email_invoice(request)
   
   send_mail('Subject heading here', 'Your main message here', 'from@example.com', ['to@example.com]', fail_silently=False,)
   
    return render(request, 'email-invoice.html')

Let's further analyze the send_mail function logic from above...

send_mail(subject, message, who the email is from, who the email is to, the email will raise an exception if there is any problem)

Please note the order of the parameters in the parentheses above (left to right):

1 - Your subject heading

2 - What is your message

3 - Who is the email coming from

4 - Who the email should be sent to

5 - Raise an exception if there is any problem

Step 4:

You will then need to make sure that you have configured the below configuration settings in your settings.py file:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'me@gmail.com' # - Choose a host email to send from
EMAIL_HOST_PASSWORD = 'app password' # - Your app password

In the above example I'm making use of the GMAIL smtp server. Of course, you can utilize something else such as Amazon SES for example.  We also need to configure our email backend accordingly to SMTP.

The default port will be port 587, this will differ according to various SMTP providers.

We need to ensure that we use TLS to secure our mail communication.

The email host user is from where we want the email's to be send from by default.

So in this example I want all my default notification emails and email invoices to be sent from a Gmail account.

Since 2016 the option to turn on less secure apps has been disabled. So, now you will need to generate an APP password on your Gmail account, and use this as your email host password.

And that's it! Happy learning!