How to Send Email in Django

How to Send Email in Django

Email is one of the essential tools in the Web Application. Sending an email with Django Web Framework is a really easy task. We can use email for the account activation, send invoices and documents.

In this tutorial, you’ll learn how to send email using Django and Python. How to send multiple emails at a time to users. Integrate SendGrid SMTP with Django. How to use Django Email console to print emails in terminals. Display Email success with Django Messages.

Quick Project Initial Setup

Create an App named emailer in your Django Project and add it to INSTALLED_APPS

Create a templates folder in the project root directory and change the template path directory in settings.py

 TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR + '/templates/',],
        ...
] 

EMAIL_BACKEND or SendGrid SMTP

At the end of settings.py file add the below code to display email in the console –

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' 

Otherwise, if you are using SendGrid SMTP add this at EOF of settings.py and change your EMAIL_HOST_PASSWORD with your SendGrid API key Password –

# Email
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIT_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = 'SG.oDN9basdaECvH5asdasw.gXVEgtD1asqSkn-EW'
How to Create SendGrid API Key

Add the path in the project urls.py file –

from django.views.generic import TemplateView

urlpatterns = [
    ...
    path('', TemplateView.as_view(template_name="home.html"), name='home'),
] 

And in the templates folder, create home.html file and bellow HTML code inside –

<html>

<head>
    <title>Send Email Django Tutorial by StudyGyaan.com</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
        integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-xl-8 offset-xl-2 py-5">
                <h1>Send Email Django Tutorial from <a href="https://studygyaan.com/">StudyGyaan.com</a></h1>
                <p class="lead">This is a demo for our tutorial dedicated to crafting working Bootstrap contact form
                    with Django.</p>

                <form id="contact-form" action="{% url 'send_email' %}" role="form">
                    {% csrf_token %}
                    <div class="messages">
                        {% if messages %}
                        {% for message in messages %}
                        <div class="alert {% if message.tags %}alert-{{ message.tags }}{% endif %}" role="alert">
                            {{ message }}
                        </div>
                        {% endfor %}
                        {% endif %}
                    </div>
                    <div class="controls">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="form_name">Name *</label>
                                    <input id="form_name" type="text" name="name" class="form-control"
                                        placeholder="Please enter your name *" required="required"
                                        data-error="Name is required.">
                                    <div class="help-block with-errors"></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="form_email">Email *</label>
                                    <input id="form_email" type="email" name="email" class="form-control"
                                        placeholder="Please enter your email *" required="required"
                                        data-error="Valid email is required.">
                                    <div class="help-block with-errors"></div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="form_message">Message *</label>
                                    <textarea id="form_message" name="message" class="form-control"
                                        placeholder="Message for me *" rows="4" required="required"
                                        data-error="Please, leave us a message."></textarea>
                                    <div class="help-block with-errors"></div>
                                </div>
                            </div>
                            <div class="col-md-12">
                                <input type="submit" class="btn btn-success btn-send" value="Send message">
                            </div>
                        </div>
                    </div>
                </form>

            </div>
        </div>
    </div>
</body>

</html> 

Sending emails in your Django Application

Here is the simple snippet for sending an email with Django.

from django.core.mail import send_mail  

send_mail(
            'subject', 
            'body of the message', 
            'sender@example.com', 
            [
                'receiver1@example.com', 
                'receiver2@example.com'
            ]
        ) 
How to send email in django

In emailers/views.py file, we will send an email with form filled data.

from django.views.generic import View
from django.shortcuts import redirect
from django.contrib import messages
from django.core.mail import send_mail, send_mass_mail

class SendFormEmail(View):

    def  get(self, request):

        # Get the form data 
        name = request.GET.get('name', None)
        email = request.GET.get('email', None)
        message = request.GET.get('message', None)

        # Send Email
        send_mail(
            'Subject - Django Email Testing', 
            'Hello ' + name + ',\n' + message, 
            'sender@example.com', # Admin
            [
                email,
            ]
        ) 

        # Redirect to same page after form submit
        messages.success(request, ('Email sent successfully.'))
        return redirect('home') 

How to send email to multiple users

Here is the code for sending an email to multiple users. We need to add email in a List like a bellow –

from django.core.mail import send_mail  

send_mail(
            'subject', 
            'body of the message', 
            'sender@example.com', 
            [
                'receiver1@example.com', 
                'receiver2@example.com'
            ]
        ) 

How to send multiple emails

We need to create a Tuple of messages and send them using send mass mail.

from django.core.mail import send_mass_mail   

message1 = ('Subject here', 'Here is the message', 'from@example.com', ['first@example.com', 'other@example.com'])
message2 = ('Another Subject', 'Here is another message', 'from@example.com', ['second@test.com'])

send_mass_mail((message1, message2), fail_silently=False)

In this tutorial, we create a project which sends email using Django. We fill the data in the form and send it using Django Email. I have printed emails terminal for easy implementation. We also learn how to send multiple emails and to multiple users.

You can also find this code on GitHub

You may also like these Email Tutorial –

Share