How to Send Email to Multiple User using Django?

Published On: 11/07/2022 | Category: Django Python

This simple article demonstrates of how to send email to multiple user using django python. This article will give you simple example of how to send email to multiple user using django admin. we will help you to give example of how to send email to multiple user using django example . you'll learn how to send email to multiple user using django python.

Let's see bellow example I explained simply about how to send email to multiple user using django python.

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject exampleapp
Step 2 : Create a App
python3 manage.py startapp sendmail

Next, you need to add it in the settings.py file as follows:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'sendmail',
]
Step 3 : Email Configuration Setup

Next step, we will modify the settings.py file and update the smtp email backends settings to configure:

settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = 'bhaveshs.aa*******@gmail.com'
EMAIL_HOST_PASSWORD = 'YOUR_APP_PASSWORD'  
Step 4 : Creating the Views

In this step, we need to create the views for performing fetch record to the database.Open the sendmail/views.py file and add:

sendmail/views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from django.core.mail import send_mail

class usersList(View):

    def get(self,request):
        users= get_user_model().objects.all()
        context = {
            'users':users
        }
        return render(request, 'usersList.html',context)

    def post(self,request,*args,**kwargs):
        if request.method == 'POST':
            users_ids = request.POST.getlist('ids[]')

            for id in users_ids:
                user = User.objects.get(pk=id)
                send_mail(
                    'Mail From Tuts-Station.com',
                    'Welcome to Tuts-Station.com',
                    '[email protected]',
                    [user.email],
                    fail_silently=False,
                )
            return redirect('users')
Step 5 : Creating the Templates

Next, open the sendmail/templates/usersList.html file and the add:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Django Send Email to Multiple Users - Tuts-Station.com</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-8">
                <div class="row">
                    <div class="col-md-9 p-0">
                        <h5><b>Django Send Email to Multiple Users - <span class="text-danger">Tuts-Station.com</span></b></h5>
                    </div>
                    <div class="col-md-3 text-right mb-2 p-0">
                        <button type="button" class="btn btn-primary send-mail btn-sm" disabled="disabled"> <i class="fa fa-share"></i> Send Mail</button>
                    </div>
                    <div class="col-md-12 success-mail p-0" style="display: none;">
                        <div class="alert alert-success">
                          Sent Mail Successfully.
                        </div>
                    </div>
                </div>
                <div class="row">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th><input type="checkbox" value="1" name="user-all" class="user-all"></th>
                                <th>Name</th>
                                <th>UserEmail</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% csrf_token %}
                            {% for user in users %}
                            <tr>
                                <td><input type="checkbox" name="ckeck_user[]" class="ckeck_user" value="{{ user.id }}"></td>
                                <td>{{ user.username}}</td>
                                <td>{{ user.email }}</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</body>

<script>
    $('.user-all').change(function (e) {
        var value = $('.user-all:checked').val();
        if (value == 1) {
            $('.ckeck_user').prop('checked',true);
            $('.send-mail').removeAttr('disabled');
        }else{
            $('.ckeck_user').prop('checked',false);
            $('.send-mail').attr('disabled','disabled');
        }
    });  

    $(".ckeck_user").change(function () {
        if ($(".ckeck_user:checked").length > 0) {
          $('.send-mail').removeAttr('disabled');
        }else{
         $('.send-mail').attr('disabled','disabled');
       }
     });

    $('.send-mail').click(function (e) {
        e.preventDefault();
        var ids = [];
        var token = $('input[name="csrfmiddlewaretoken"]').val();

        $('.ckeck_user:checked').each(function(i){
            ids[i] = $(this).val();
        })

        if (ids != '') {
            $(this).attr("disabled", true);
            $(this).html('<i class="fa fa-spinner fa-spin"></i> Send Mail');
            $.ajax({
                url: '{% url "users" %}',
                type: 'POST',
                data: {
                    ids:ids,
                    csrfmiddlewaretoken: token,
                },
                success: function (data) {
                    $('.success-mail').css('display','block');
                    $('.ckeck_user, .user-all').prop('checked',false);
                    $('.send-mail').attr("disabled", false);
                    $('.send-mail').html('<i class="fa fa-share"></i> Send Mail');
                }
            });
        }
    });
</script>
</html>
Step 6 : Creating Urls

In this section, we’ll create the urls to access our views.Go to the urls.py sendmail/urls.py file and update it as follows:

sendmail/urls.py
from django.urls import path
from sendmail.views import EmailAttachementView

urlpatterns = [
    path('users', usersList.as_view(), name='users'),
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

exampleapp/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('sendmail.urls')),
]
Step 7 : Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the url address bar with a web browser.

http://localhost:8000/send-email
Output

I Hope It will help you....