Integrating SendGrid with Django Rest Framework

Whenever we develop Web or Mobile Applications, there is always a need for sending emails for various reasons through the developed platform. Some of the reasons why we need to integrate email service are:
  1. Sending email for email id verification.
  2. Sending an email to the registered email id to regain access after the loss of password.
  3. Sending an invitation email to join the platform.
You can find a few use cases here.
There are multiple services around through which we can integrate Email Service in our platform. This article will be covering the integration of one of the most popular emailing services Twilio’s SendGrid.

Prerequisites

This article assumes that you’ve theoretical and practical knowledge of Python, Django Rest Framework, and implementing third party libraries in it.

Preface

This article is going to be covering how to set-up a SendGrid account and implement a SendGrid Emailing Service at the server-side.
We will follow the steps below in order:-
  1. Setting up a SendGrid account.
  2. Designing a dynamic transactional template in SendGrid.
  3. Installing SendGrid library in Django.
  4. Setting up SendGrid in Django.
  5. Creating API for sending available email templates in SendGrid.
Now let’s start the integration process.

Setting up a SendGrid account

For getting started with sending email through SendGrid, we will require an API key which will be used in our Django SendGrid integration. We need to create a SendGrid account by Signing up or by Logging in to your SendGrid account. In the left sidebar, select Settings > API keys > Create API Key.
Enter a name for your API key. Choose the API key access whichever is suitable for your requirement. Full Access permissions give the key the ability to perform all the necessary email sending functions. If you prefer to create a key that has very specific permissions, then select “Restricted Access” and configure your access as needed.
When you click the “Create & View” button you will be presented with your key. This key will never be shown again, so you need to click on it to copy it to the clipboard, and then paste it in a secure document so that you can use it later. If you lose your key, you will need to generate a brand new one. Once you have saved your key, you can click the “Done” button.
Note: Do not share your SendGrid API Key with anyone as it may be misused.

Designing a dynamic transactional template

For creating a dynamic template, In the left sidebar, select Email API > Dynamic Templates > Create a Dynamic Template. Enter a name for your template and click on “Save”.
To begin with, editing your new template, click on “Add Version”. Then Select a Design template as per your requirements or you can create new blank templates, Lastly, you need to Select an Editor (how you will be editing the template by Code Editor or by Design Editor)
Now that you have the version we can start editing the template as per our need.

Starting with the development process

1. Installation
pip3 install sendgrid
2. Adding required values in settings.py file for PayU
# Twilio Sendgrid API key

SENDGRID_API_KEY = 'YOUR SENDGRID API KEY'

# setting default email for sending email through sendgrid

DEFAULT_FROM_EMAIL = "YOUR SENDER MAIL ID"
3. Creating a class-based view for sending email using Mail helper Class
import sendgrid

from sendgrid.helpers.mail import (Mail, Email,Personalization)

from python_http_client import exceptions

from twilio_sendgrid_integration.settings import DEFAULT_FROM_EMAIL, SENDGRID_API_KEY

sg = sendgrid.SendGridAPIClient(SENDGRID_API_KEY)

class MailSenderAPIView(GenericAPIView):

   def send_mail(self, template_id, sender, recipient, data_dict):

       mail = Mail()

       mail.template_id = template_id

       mail.from_email = Email(sender)

       personalization = Personalization()

       personalization.add_to(Email(recipient))

       personalization.dynamic_template_data = data_dict

       mail.add_personalization(personalization)

       try:

           response = sg.client.mail.send.post(request_body=mail.get())

       except exceptions.BadRequestsError as e:

           print("INSIDE")

           print(e.body)

           exit()

       print(response.status_code)

       print(response.body)

       print(response.headers)

def post(self, request):

       recepient_email = request.data['recepient_email']

       subject = request.data['subject']

       fullname = request.data['fullname']

       body = request.data['body']

 template_id = "d-1772e8ac6b5442e68975394ea71a4957"

       sender = DEFAULT_FROM_EMAIL

       data_dict = {"subject": subject, "user_name": fullname, "body": body}

       MailSenderAPIView.send_mail(self, template_id, sender, recepient_email, data_dict)

       return Response({"status_code": status.HTTP_200_OK, "message": "Mail sent successfully."})
4. Creating endpoint for the created Class view for sending an email
from django.conf.urls import url

from .views import MailSenderAPIView

urlpatterns = [

   url('sendTemplateEmail', MailSenderAPIView.as_view(), name="mail-sender"),

]
You can find the whole implementation here.

subscribe to our newsletter

   
   

About Author

Related Posts

Leave a Comment

SES-email-template