DEV Community

Yash Patel
Yash Patel

Posted on • Edited 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 smtp.gmail.com because let's take and example Gmail’s SMTP server address is smtp.gmail.com, and Twilio Send Grids is smtp.sendgrid.com. 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 manage.py startapp main

Directory previewAlt Text

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

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

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

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'gmail account email id'
EMAIL_HOST_PASSWORD = 'Your gmail password'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
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 form.py file in mail folder and write code below code

form.py

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 views.py file and write below code

views.py

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():
            # form.save()
            # send_mail(subject, message[fname, lname, email, phonenumber, subject, message], sedner, recipient)

            subject = "Contact form inquiry"
            body = {
                'first_name': form.cleaned_data['first_name'],
                'last_name':form.cleaned_data['last_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 = ['gameforyash@gmail.com']

            try:
                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 = {
        'form':form,
    }
    return render(request, "home/index.html", context)
Enter fullscreen mode Exit fullscreen mode

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

Step 11 --> Open urls.py 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 urls.py created in main folder to emails>url.py as shown below

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

urlpatterns = [
    path('admin/', admin.site.urls),
    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">

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet"
            integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
        <style>
            .marg {
                margin: 20%;
            }
        </style>
    </head>

    <body>
        <dev class="marg">
            <form class="form-contact contact_form container" action="{% url 'home' %}" method="post" id="contactForm"
                novalidate="novalidate">
                <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>
                    </div>

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

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

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

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

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

        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf"
            crossorigin="anonymous"></script>
    </body>

</html>
Enter fullscreen mode Exit fullscreen mode

Step 15 --> Now start your django server using command python manage.py 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)

Collapse
 
danidiaztech profile image
Daniel Diaz

Good Post!

Collapse
 
yashpatel_py profile image
Yash Patel

Thank you so much ❤