How to Send Email using Django REST framework?

Published On: 28/12/2022 | Category: Django


Hi Dev,

I am going to explain you example of how to send email using django rest framework. let’s discuss about send email using django rest framework. it's simple example of django rest framework send email example. it's simple example of how to send email using drf. Let's see bellow example django rest framework send mail.

Emails are frequently delivered to users in a range of professions using the Simple Mail Transfer Protocol (SMTP), which is a widely utilised approach. Open-source frameworks like the Python-based web application Django provide users additional flexibility when sending emails by utilising functions and expressions.

Here i will give you we will help you to give example of how to send email using django rest framework. So let's see the bellow example:

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 example
Step 2: Create a App
cd example
django-admin startapp core

Step 3: Install required library

Install Django and its prerequisites:

pip install djangorestframework

Step 4: Update settings.py

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',
    'core',

    'rest_framework'
]

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = 'your[email protected]'
EMAIL_HOST_PASSWORD = 'YOUR_APP_PASSWORD'  

Step 5: Creating the Views

In this step, we need to configure views. open the core/views.py file and add:

core/views.py
from rest_framework.views import APIView
from django.conf import settings
from django.core.mail import send_mail
from rest_framework.response import Response

# Create View
class EmailAPI(APIView):
    def get(self, request):
        subject = self.request.GET.get('subject')
        txt_ = self.request.GET.get('text')
        html_ = self.request.GET.get('html')
        recipient_list = self.request.GET.get('recipient_list')
        from_email = settings.DEFAULT_FROM_EMAIL

        if subject is None and txt_ is None and html_ is None and recipient_list is None:
            return Response({'msg': 'There must be a subject, a recipient list, and either HTML or Text.'}, status=200)
        elif html_ is not None and txt_ is not None:
            return Response({'msg': 'You can either use HTML or Text.'}, status=200)
        elif html_ is None and txt_ is None:
            return Response({'msg': 'Either HTML or Text is required.'}, status=200)
        elif recipient_list is None:
            return Response({'msg': 'Recipient List required.'}, status=200)
        elif subject is None:
            return Response({'msg': 'Subject required.'}, status=200)
        else:
            sent_mail = send_mail(
                subject,
                txt_,
                from_email,
                recipient_list.split(','),
                html_message=html_,
                fail_silently=False,
            )
            return Response({'msg': sent_mail}, status=200)

Step 6: Creating URLs

In this section, we need a urls.py file within the core app however Django doesn't create one for us with the startapp command. Create core/urls.py with your text editor and paste below code.

core/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('send-email', views.EmailAPI.as_view()),
]

Next, we require to add a URL path for our example app which can be done by importing include and setting a path for it.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
]

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

Send Text email

Visit the following website with the proper parameters to send a text message.

http://localhost:8000/send-email?subject=Demo&text=Welcome to [email protected]

Postman send mail request.



Output

Postman send mail request.

Sending HTML emails

Let's send an HTML email after that. Use HTML in the URL rather than text. Here is an HTML test link.

http://localhost:8000/send-email/?subject=Demo&html=<h1>Welcome to Tuts-Station.com</h1>[email protected]


Output

I Hope It will help you....