Django Email services with Google SMTP

Django Email services with Google SMTP

In this Tutorial we are going to learn how to build an email service using django and google smtp. It is believed you already have basic knowledge of django and django restframework.

At the end of this tutorial we should know

  • How to setup google mail smtp

  • How to send email via django

How to setup google mail smtp

Login to your google account

click on Manage your Google Account

Navigate to Security and click on 2-Step Verification and do all necessary verification using your phone number.

After that click on App passwords it will generate a password which you can use to log in to your email smtp server. Please take Note Once the password has been generated, do well to copy the password somewhere safe. because after you have closed the page, you won't be able to open it again to view the password. So please copy and save in a safe place, because it will be needed to login to your google smtp server

Starting Django email services

First of all I like to start with creating a virtual environment, now run the following:

python3 -m venv root/venv
source venv/bin/activate

Here I used python3 but if your machine has an older version you can use python instead. well now my virtual environment has been created and activated. We must have installed django and django restframework. and must have started our project. I am going to go ahead and name mine DJangoEmailService

now run the following

cd DjangoEmailService
python manage.py startapp email_app

Now go to DjangoEmailService folder containing the settings.py and add the following in settings.py

INSTALLED_APPS = [
    ...
    'email_app',
]

In settings.py add the following

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = os.environ.get("YOUR_EMAIL_ADDRESS")
EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_APP_PASSWORD")

Remember the app password we copied while setting up google mail for smtp? That is what we are going to use in the EMAIL_HOST_PASSWORD while we use the email address in EMAIL_HOST_USER .

In email_app/models.py add the following

from django.db import models

class EmailMessenger(models.Model) :
    subject = models.CharField(max_length=25)
    body = models.CharField(max_length=200)
    to_email = models.EmailField()

    def __str__(self) :
        return f'{self.subject}'

created models which we would use to store the mails to database.

In email_app/admin add

from django.contrib import admin
from .models import EmailMessenger

admin.site.register(EmailMessenger)

run the following

python manage.py makemigrations
python manage.py migrate

create utils.py in email_app and add :

from django.core.mail import EmailMessage
from django.conf import settings

class Util :
    def send_email(data):
        email = EmailMessage(
            data['email_subject'],
            data['email_body'],#Email body
            settings.EMAIL_HOST_USER,#The address to which the email is being sent from
            [data['to_email']] #email address receiving the email
        )
        email.send(fail_silently=False)

This the function that will be used to send email to whoever you want to, email addressing receiving the email has to be an iterable so a list or a tuple.

create serializers.py in email_app and add the following

from rest_framework import serializers
from .models import EmailMessenger
from .utils import Util

class EmailMessengerSerializers(serializers.ModelSerializer) :
    class Meta :
        model = EmailMessenger
        fields = '__all__'

    def create(self, data):
        subject = data.get("subject")
        body = data.get("body")
        to_email = data.get("to_email")
        email_data = {'email_body':body, "to_email":to_email,"email_subject":subject}
        Util.send_email(email_data)

        email = EmailMessenger.objects.create(subject=subject, body=body, to_email=to_email)
        return email

then create an api.py in email_app then add the following

from .serializers import EmailMessengerSerializers
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response


class EmailMessengerAPI(GenericAPIView) :
    serializer_class = EmailMessengerSerializers

    def post(self, request, *args, **kwargs) :
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response({
            "message":"email has been sent successfully",
            "success":True
        })

create urls.py in email_app, then go to DjangoEmailService/urls.py and add

path("", include("email_app.urls"))

in email_app/urls.py add the following

from .api import EmailMessengerAPI
from django.urls import include, path

urlpatterns = [
    path("api/send_email",EmailMessengerAPI.as_view())
]

Congratulations!! You have successfully built an email service which can successfully send emails to different email address of your choice. to test this out go over to postman

That email address should receive your email now.

Conclusion

Now you have learned everything there is to know about building an email service in django or django rest_framework using google smtp. You can now apply this to your app. You can also check out the full code on Github.