Managing email notifications effectively is a crucial aspect of streamlined communication.
In the realm of Gmail, integrating the capabilities of Google Pub/Sub with Django offers a powerful solution for controlling the flow of emails through the watch and stop requests on your mailbox. Any action was taken in the mailbox like receive email, set email, or draft email you want to know automatically instead of calling fetch email API again and again, so in this case watch request will be going to help you.
This fusion of technologies empowers users to intelligently monitor and pause email notifications, enhancing control and productivity within Gmail.
In this blog, we’ll delve into the integration of Google Pub/Sub with Django, exploring how this pairing facilitates the implementation of watch and stop requests on your Gmail mailbox.
By harnessing the robust functionalities of these platforms, you’ll gain insights into optimizing email management within your Django application, fostering a more efficient and tailored email experience.
Before we discuss further I highly recommend that you should go through my previous blog “Enhance Your Django Project with Gmail Integration”. This blog is nothing but an extension of my previous blog.
Absolutely, let’s refine those prerequisites for integrating Gmail into your Django project:
Ensure you have an existing Django project or create a new one for integrating Gmail functionality. Verify that Django is properly installed and configured within your project structure.
Access to a Google account is necessary to log in to the Google Cloud Console and manage API credentials.
Create a distinct project within the Google Cloud Console. This project will serve as the platform for enabling the Gmail API and generating OAuth 2.0 credentials.
Navigate to the “APIs & Services” section within your Google Cloud Console project and activate the Gmail API. This step enables your project to access Gmail’s functionalities.
Generate OAuth 2.0 Client IDs for a web application within your Google Cloud Console project. These credentials are pivotal for authenticating and authorizing your Django application to interact with the Gmail API securely.
Pub/Sub, short for “Publish/Subscribe” is a messaging pattern used in software architecture to facilitate communication between different components or systems. At its core, Google Pub/Sub involves the distribution of messages from publishers to subscribers without them directly knowing about each other.
🔸 Publishers
These are entities or components responsible for creating and sending messages. They publish messages on specific topics.
🔸 Topics
Messages are categorized and organized into topics. Publishers send messages to these topics.
🔸 Subscribers
These are entities or components interested in receiving messages. Subscribers “subscribe” to specific topics to receive messages published on those topics.
🔸 Message Broker
The intermediary system managing the communication between publishers and subscribers. It ensures that messages published to topics are delivered to all relevant subscribers.
Pub/Sub systems allow for scalable, asynchronous communication between various parts of an application or between different applications. It enables the decoupling of components, allowing them to communicate without direct dependencies, thereby enhancing flexibility and scalability.
For instance, the context of Google Cloud Platform’s Pub/Sub service provides a fully managed real-time messaging service that allows you to create topics, publish messages to these topics, and have subscribers receive these messages.
This type of architecture is commonly used in building scalable and distributed applications where different services need to communicate without direct coupling.
Before we go further we need to set up Google Pub/sub also you need to create a project and enable Gmail APIs my previous blog will help you.
So let’s move ahead step by step:
➡️ Go to “Pub/Sub” and then click on “Topics”. A list of topics window will open then click on “Create Topic”.
➡️ Enter a unique name for your topic and optionally a description then click “Create”.
➡️ Go to the topic you just created, and click on “Create Subscription”.
Enter a name for your subscription and choose a delivery type,
Push: Messages are delivered to an endpoint you specify.
Pull: Messages are retrieved by your application when needed.
We will choose the push delivery type and provide the endpoint.
➡️ Hence, we configure Ngrok, which is a multiplatform of tunneling, reverse proxy software that establishes secure tunnels from a public endpoint to a locally running network service. It allows developers to expose a local server to the internet, bypassing NATs and firewalls, and enabling temporary access for testing or demonstration purposes. So provide an endpoint in the endpoint URL field.
🔸 Message Retention:
Set a message retention period to control how long messages are stored before being deleted.
🔸 Message Ordering:
While Pub/Sub generally delivers messages in the order they’re published, it doesn’t guarantee strict ordering.
🔸 Dead Letter Queues:
Configure dead letter queues to handle messages that can’t be processed successfully.
🔸 Security:
Consider security measures like authentication and encryption to protect sensitive data.
After setting up let’s have some code, before the watch request we need to have an OAuth2 access token with the necessary permission.
headers = {'Authorization': f'Bearer {access_token_response["access_token"]}'}
personal_info_response = requests.get(GOOGLE_USER_INFO_URL, headers-headers)
personal_info_response = personal_info_response.json()
watch_request_url =
"https://gmail.googleapis.com/gmail/v1/users/{}/watch".format(personal_info_response["email"])
watch_request_data = {
}
'labelIds': ['INBOX'],
'topicName': getenv('PUB_SUB_TOPIC'),
'labelFilterBehavior': 'INCLUDE'
requests.post(watch_request_url, headers-headers, data=watch_request_data)
Above code snippet, we create headers with access tokens. Next, we create a watch request URL with the user’s email and also create a watch request payload.
labelIds: Specifies which Gmail labels to watch (in this case, only the ‘INBOX’ label).
POST request
requests.post(watch_request_url, headers=headers,data=watch_request_data)
This sends a POST request to the constructed watch request URL, initiating the watch request.
The headers dictionary provides authorization for the request.
The watch_request_data dictionary specifies the watch request parameters.
class GmailWatchAPIView(CreateAPIView):
"""
Class for creation a gmail watch api.
"""
permission_classes = ()
authentication_classes = ()
serializer_class = GmailWatchSerializer
throttle_classes = ()
def post(self, request, *args, **kwargs):
"""
POST method used for gmail watch.
"""
data = request.data.get("message")
encoded_data = data.get("data")
decoded_data = base64.b64decode(encoded_data).decode("utf-8")
print("DECODED <><><><>", decoded_data)
return Response({"SUCCESS": "SUCCESS"})
This code defines a webhook endpoint, which is a URL that Pub/Sub can call to deliver notifications (messages) to your application.
It acts as a receiver for messages from Google Pub/Sub, handling incoming events and triggering actions accordingly.
🔸 Subscription
The webhook is likely associated with a Google Pub/Sub subscription that was configured to send notifications to this endpoint.
🔸 Message Delivery
When a message is published to the topic associated with the subscription, Pub/Sub sends a POST request to this webhook endpoint with the message payload.
GmailWatchAPIView This class creates a Django view specifically designed to handle incoming Pub/Sub messages related to Gmail watch notifications.
post(self, request, *args, **kwargs) This method is triggered when a POST request (from Pub/Sub) is received.
data = request.data.get(“message”) It extracts the message payload from the request data.
encoded_data = data.get(“data”) It retrieves the encoded Base64 data within the message.
decoded_data = base64.b64decode(encoded_data).decode(“utf-8”) It decodes the Base64 data into a readable string format.
print(“DECODED <><><><>”, decoded_data) This line likely represents a placeholder for further processing of the decoded data (e.g., extracting information about Gmail events and performing actions).
This code defines a Django view for revoking Google access tokens and stopping associated Gmail watch requests using Google Pub/Sub.
class RevokeGoogleAccessTokenAPIView(RetrieveAPIView):
"""
Class for creation a revoke google access token api.
"""
permission_classes = ()
authentication_classes = ()
throttle_classes = ()
def get(self, request, *args, **kwargs):
"""
GET function revoke the Google access token.
"""
email = request.GET.get("email", None)
if email:
google_info = GoogleRequestModel.objects.filter(email=email).last()
if google_info:
headers = {
'Authorization': f'Bearer {google_info.access_token}'
}
stop_request_response = requests.post(GMAIL_STOP_REQUEST_URL.format(email), headers=headers)
revoke_url = GOOGLE_REVOKE_TOKEN_URL
# Construct the token revocation request
revoke_params = {
'token': google_info.access_token
}
response = requests.post(revoke_url, params=revoke_params)
if response.status_code == 200 and stop_request_response.status_code == 204:
google_info.delete()
return Response({"message": "Access token revoked and watch request stopped successfully."})
else:
return Response({"message": "Failed to revoke the access token."})
else:
return Response({"message": "email address is required!"})
Before revoking the access token we need to stop Gmail watch requests first.
So constructs the stop request URL, the URL with the user’s email to target the specific watch request.
Sends the Stop Request:
Send a POST request to the URL to terminate the watch request.
Revoke Access Token:
Constructs the Revocation Request:
revoke_url sets the URL for Google’s token revocation endpoint.
revoke_params = {‘token’: google_info.access_token}: Prepares parameters with the access token to be revoked.
Sends the Revocation Request:
requests.post(revoke_url, params=revoke_params): Sends a POST request to Google’s endpoint to revoke the token.
Access token has been revoked and also your watch request is stopped, pub/sub won’t trigger webhook.
In this blog, we have explained how to monitor changes in your Gmail inbox using Google Pub/Sub and Django. Firstly, we have discussed the process of setting up a Gmail watch request which involves using the Gmail API to start monitoring your inbox. This feature allows users to receive real-time notifications whenever new emails arrive or labels are modified.
Next, we have looked at integrating Google Pub/Sub which involves configuring Pub/Sub topics and subscriptions to receive these notifications as messages. This integration provides the much-needed flexibility and scalability to effectively process incoming alerts.
Additionally, we have also explained how to build a Django API for stop requests. This API endpoint enables users to revoke their Google access tokens and halt the Gmail watch request associated with them. With this feature, users can conveniently manage their Gmail monitoring preferences within their Django application.
How to Effectively Hire and Manage A Remote Team of Developers
Download NowMindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork