DEV Community

Yash Patel
Yash Patel

Posted on • Updated on

How to send e-mail in django ?

Alt Text
In django we can send e-mail using SMTP (Simple Mail Transfer Protocol) service which is inbuilt package in python and also in django.

What is smtp ?

  • SMTP (Simple Mail Transfer Protocol) is service that provides service to send, receive, and or relay outgoing mail between senders and receivers.

  • SMTP service takes your client email address(you can also give multiple email address) which you are using and it is formatted as because let's take and example Gmail’s SMTP server address is, and Twilio Send Grids is You can generally find your SMTP server address in the account or settings section of your mail client.

Django email sending setup

Step 1 --> create one folder and name it as django_email

Step 2 --> Create django project using below command
django-admin startproject emails .
Directory previewAlt Text

Step 3 --> Create django app in project created from above step and use command python startapp main

Directory previewAlt Text

Step 4 --> Now install app in and this file will be in emails folder
Directory previewAlt Text

Step 5 --> Now you need to migrate the project using command
python migrate

Step 6 --> Go in and go at the bottom and write code under static variable

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST_USER = 'gmail account email id'
EMAIL_HOST_PASSWORD = 'Your gmail password'
Enter fullscreen mode Exit fullscreen mode

Here in variable EMAIL_HOST_USER you need to write the email id which have two step verification off because we need to make some settings change on your g-mail account. And In variable EMAIL_HOST_PASSWORD you need you write your g-mail account password.

Step 7 --> Now open your favorite browser and follow below steps

  • Go in option Account Alt Text

  • Go in option Security and search for Less secure app access and turn that on because if you will not turn that on then django will not able to send the mail.
    Directory previewAlt Text

Step 8 --> Now create file in mail folder and write code below code

from django import forms

class ContactMeForm(forms.Form):
    first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter first name'}), required=True)
    last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter last name'}), required=True)
    emailid = forms.EmailField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter email id'}), required=True)
    phone_number = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter phone number'}))
    subject = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter subject'}), required=True)
    message = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control', 'placeholder':'Enter Message'}), required=True)
Enter fullscreen mode Exit fullscreen mode

Step 9 --> Now go in file and write below code

from django.shortcuts import render
from main.form import ContactMeForm
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse
from django.contrib import messages

def home(request):
    form = ContactMeForm()

    if request.method == 'POST':
        form = ContactMeForm(request.POST)
        if form.is_valid():
            # send_mail(subject, message[fname, lname, email, phonenumber, subject, message], sedner, recipient)

            subject = "Contact form inquiry"
            body = {
                'first_name': form.cleaned_data['first_name'],
                'email': form.cleaned_data['emailid'],
                'phonenumber': form.cleaned_data['phone_number'],
                'subject': form.cleaned_data['subject'],
                'message': form.cleaned_data['message'],

            message = '\n'.join(body.values())

            sender = form.cleaned_data['emailid']
            recipient = ['']

                send_mail(subject, message, sender, recipient, fail_silently=True)

            except BadHeaderError:
                return HttpResponse("Invalid header found.")

            messages.success(request, "Your respoce has been submited successfully")
    context = {
    return render(request, "home/index.html", context)
Enter fullscreen mode Exit fullscreen mode

Step 10 --> Now create file in main folder
Directory previewAlt Text

Step 11 --> Open created in main folder and write below code

from django.urls import path
from main import views

urlpatterns = [
    path('', views.home, name="home"),

Enter fullscreen mode Exit fullscreen mode

Step 12 --> Now register created in main folder to emails> as shown below

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('main.urls'))
Enter fullscreen mode Exit fullscreen mode

Step 13 --> Now create templates folder in main folder and create home folder in templates folder and create index.html in home folder

SOME THING LIKE THIS main>templates>home>index.html
Directory previewAlt Text

Step 14 --> Open index.html and write below code

<!DOCTYPE html>
<html lang="en">

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="" rel="stylesheet"
            integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
            .marg {
                margin: 20%;

        <dev class="marg">
            <form class="form-contact contact_form container" action="{% url 'home' %}" method="post" id="contactForm"
                <h1>Contact us form</h1>
                {% csrf_token %}
                <div class="row">
                    <div class="col-sm-6">
                        <div class="form-group">
                            <label for="first_name">Enter first name</label>
                            {{ form.first_name }}

                    <div class="col-sm-6">
                        <div class="form-group">
                            <label for="last_name">Enter last name</label>
                            {{ form.last_name }}

                    <div class="col-6">
                        <div class="form-group">
                            <label for="email">Enter Email id</label>
                            {{ form.emailid }}

                    <div class="col-6">
                        <div class="form-group">
                            <label for="phone_number">Enter phone number</label>

                    <div class="col-12">
                        <div class="form-group">
                            <label for="subject">Subject</label>

                    <div class="col-12">
                        <div class="form-group">
                            <label for="Message">Enter Message</label>
                <div class="form-group mt-lg-3">
                    <button type="submit" class="btn btn-outline-success">Send Message</button>

        <script src=""

Enter fullscreen mode Exit fullscreen mode

Step 15 --> Now start your django server using command python runserver

**Step 16 --> Fill the data and click on submit button and see your mail mail box you must see mail

Alt Text

mail receivedAlt Text

If you like this shot django mail sending tutorial then please like this blog and if you have any doubts the let me know in discussion box

Top comments (2)

danidiaztech profile image
Daniel Diaz

Good Post!

yashpatel_py profile image
Yash Patel

Thank you so much ❤