Gmail Watch and Stop Request on Mailbox Using Google Pub/Sub with Django

Introduction

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.

Prerequisites

Absolutely, let’s refine those prerequisites for integrating Gmail into your Django project:

✅ 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.

✅ Google Account

Access to a Google account is necessary to log in to the Google Cloud Console and manage API credentials.

✅ Google Cloud Console Project

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.

✅ Gmail API Activation

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.

✅ OAuth 2.0 Credentials

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.

What is Pub/Sub?

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.

Quick Set Up of Pub/Sub

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”.

Pubsub.png
Fig: Gmail Watch Demo

➡️ Enter a unique name for your topic and optionally a description then click “Create”.

Google-Pubsub.png
Fig: Create Topic

➡️ 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.

Pubsub-Cloud.png
Fig: Add Subscription to Topic

➡️ 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.

Pubsub-Subscription.png
Fig: Create Pub/Sub Topic

Additional Considerations

🔸 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.

Accelerate in Django! Participate in our Hiring Process for Forward-Thinking Projects.

Watch Request On Mailbox

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).

topicName: The name of the Pub/Sub topic where notifications will be sent.
labelFilterBehavior: Determines how labels are used for filtering (‘INCLUDE’ means only watch messages with the specified labels).

Initiating Watch Request

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.

Define Your Webhook

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.

Pub/Sub Integration

🔸 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 Method

post(self, request, *args, **kwargs) This method is triggered when a POST request (from Pub/Sub) is received.

✅ Retrieving Data

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.

✅ Decoding Data

decoded_data = base64.b64decode(encoded_data).decode(“utf-8”) It decodes the Base64 data into a readable string format.

✅ Processing Data

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).

Stop Request On Mailbox

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.

coma

Conclusion

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.

Keep Reading

Keep Reading

Struggling with EHR integration? Learn about next-gen solutions in our upcoming webinar on Mar 6, at 11 AM EST.

Register Now

Let's create something together!