Innovate anywhere, anytime withruncode.io Your cloud-based dev studio.
Django

Sending Emails Using Sendgrid on Heroku for a Django App

2022-07-19

You can send automated email campaigns in a simple and easy manner by using Sendgrid on Heroku for your Django App.

Installation:
First, you need to deploy your Django app on Heroku and then you can directly add Sendgrid to your Heroku application from Heroku ADD-ONS.

Or You can integrate sendgrid add-on directly from your terminal by using Heroku CLI(Heroku Command Line). So, first you should install Heroku Toolbelt. 

Heroku Toolbelt Installation:

wget -O- https://toolbelt.heroku.com/install-ubuntu.sh | sh

You can directly specify the above line in your terminal for installing Heroku Toolbelt.

Heroku Version:
Check your heroku version, to verify whether toolbelt is installaed or not.

$ heroku --version
heroku-toolbelt/3.43.3 (x86_64-linux) ruby/1.9.3

To Know Heroku File Location:
By using 'which' command you can see your Heroku file location easily.

$ which heroku
/usr/local/heroku/bin/heroku

Heroku Login:
Login to heroku API by using your login creadentials like email and password and these details will be saved for future purpose.

$ heroku login
Enter your Heroku credentials.
Email: [email protected]
Password:

After logged into heroku CLI you can add heroku add-ons by using below command:

$ heroku addons:create sendgrid:starter

How to get Sendgrid Username & Password: 
Once sendgrid has been successfully added to your Heroku, you can get SENDGRID_USERNAME, SENDGRID_PASSWORD easily by using Heroku config:get command

$ heroku config:get SENDGRID_USERNAME

[email protected]
$ heroku config:get SENDGRID_PASSWORD

password

Example:
For sending email campaigns, initially you should add your 'Sendgrid_API_Key' and 'To_Email'. So, all the notification emails will be sent to the specified 'To_Email'. The following code is an example of how to send emails by using Sendgrid

import sendgrid

sg = sendgrid.SendGridClient(YOUR_SENDGRID_API_KEY')
message = sendgrid.Mail()
message.add_to('To_Email')
message.set_from('User_Name')
message.set_subject('Email_Subject')
message.set_html('Body')
sg.send(message)