Email Open Rate Using Python and Django

Most of the marketing tools now a day allows you to monitor your email open rate kinda like WhatsApp’s blue tick in this article we will learn how to do the same using python

Prerequisites

Django — it's a web development framework we will be using for our API

Core Logic in layman’s terms

As we already know we can add images to our emails these images can be added using local files or a URL. If we add an image using a URL when the email is opened by the email client (Gmail, etc.…) it makes a GET request to the image URL

We can capture this using our code and using a unique URL for every email sent we can see which mail was opened

Let’s start coding

you can clone the repo from my GitHub to follow along

install all the dependencies ( I recommend doing this in a virtual environment )

pip install -r requirements.txt

Code-Explanation (Django)

api/app/models.py

it contains our database schema. you can learn more about models here

our Django app contains a table named ImageHash with i_hash, status as columns

api/app/views.py

views contain the main logic of loading the image and updating the status

api/app/urls.py

here each URL is mapped to its specific view

run the Django server

cd api/
python manage.py runserver

as we are running this on a local machine the generated URL will contain localhost which won't be accessible by Gmail or any other email client

so to get the public URL we can either host the API or (for testing purpose) we can just tunnel our local port

we will use Ngrok to tunnel our port 8000

./ngrok http 8000

https://94be8bde6237.ngrok.io is the public URL for local port 8000

api_wrapper.py

we have an API wrapper as well to make our API interaction much easier

script.py

let's use our API.

create a MailStatus object with our Ngrok URL

from api_wrapper import MailStatus 
# create email status object
ms = MailStatus(url="https://94be8bde6237.ngrok.io")

get the unique hash and make a URL this URL can be sent over email in an image tag

# get unique hash 
i_hash = ms.getHash()
# combine that hash and make a url
img = ms.getImgURL(i_hash=i_hash)

# this 'll print false if hash is not used
print("status:",ms.hashStatus(i_hash))

send an email with this image tag

check your inbox and open the email

check the email status in your script and it should print True

print("status:",ms.hashStatus(i_hash))

Conclusion

congrats we have successfully tested our open rate logic using Django and python

If you have any query feel free to comment or connect

AI and Blockchain