Python Django: Google Authentication and Fetching mails from scratch


Python Django is a powerful web framework known for its ability to simplify the development process and enable developers to create robust and feature−rich web applications. In this article, we'll explore the integration of two key features in Django: Google authentication and fetching emails. By seamlessly combining Django's integration with Google authentication and leveraging the Google API client library, developers can offer users a secure login experience using their Google credentials. Additionally, users can conveniently fetch and interact with their Gmail messages within the Django application.

This article will provide step−by−step guidance on implementing Google authentication and email fetching from scratch, accompanied by examples and outputs. Whether you're building a messaging platform, an email−based application, or seeking to enhance your Django project, this article equips you with the knowledge and tools necessary for seamlessly incorporating Google authentication and email fetching into your Django projects.

To get started, make sure you have Django and Django−all auth installed in your Python environment. You can install them using pip:

pip install django django-allauth

Once you have installed the required packages, you can start setting up Google authentication in your Django application. First, open your project's settings.py file and add 'allauth' and 'allauth.account' to the INSTALLED_APPS list:

INSTALLED_APPS = [
    ...
    'allauth',
    'allauth.account',
    ...
]

Next, configure the authentication backend by adding the following lines to your settings.py file:

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend',]

After configuring the authentication backend, the next step is to provide the Google OAuth credentials in your settings.py file.

Here’s an example:

SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': ['profile', 'email'],
        'AUTH_PARAMS': {'access_type': 'online'},
    }
}

Make sure to replace the 'client_id' and 'client_secret' values with your own credentials obtained from the Google Developers Console.

With the authentication setup complete, we can now create the necessary views and templates for the login and logout functionality. Here’s an example code:

from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from rest_auth.registration.views import SocialLoginView

class GoogleLogin(SocialLoginView):
    adapter_class = GoogleOAuth2Adapter
    client_class = OAuth2Client

In your urls.py file, include the following code:

from .views import GoogleLogin

urlpatterns = [
    ...
    path('accounts/google/login/', GoogleLogin.as_view(), name='google_login'),
    ...
]

Now, we can include a link or button in your template to initiate the Google authentication process. For example

<a href="{% url 'google_login' %}">Login with Google</a>

After clicking the provided link, we are redirected to the Google login page to authenticate using our own Google credentials. Upon successful authentication, we seamlessly return to our Django application, ready to explore its features. Now, let's open Python Django and the Google API client library to fetch emails from Gmail, simplifying the process of connecting with various Google services.

First, make sure we have the google−api−python−client package installed:

pip install google-api-python-client

To access Gmail, we need to enable the Gmail API in the Google Developers Console. Create a new project if you haven't already, enable the Gmail API, and generate API credentials (OAuth client ID) for your project.

We can authenticate and authorize access to the Gmail API using the API credentials once we have them. Create a file called gmail.py in your Django project and add the following code:

import os
import pickle
import base64
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build

# Define the SCOPES required for accessing Gmail
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def get_gmail_service():
    # Load or create the token file for authentication
    token_file = 'token.pickle'
    creds = None

    if os.path.exists(token_file):
        with open(token_file, 'rb') as token:
            creds = pickle.load(token)
    
    # If there are no valid credentials, authenticate the user
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        
        # Save the credentials for future use
        with open(token_file, 'wb') as token:
            pickle.dump(creds, token)
    
    # Create a Gmail service instance
    service = build('gmail', 'v1', credentials=creds)
    
    return service

def fetch_emails():
    # Get the Gmail service
    service = get_gmail_service()

    # Fetch the emails from the user's Gmail inbox
    results = service.users().messages().list(userId='me', labelIds=['INBOX']).execute()
    emails = results.get('messages', [])

    if not emails:
        print('No emails found.')
    else:
        print('Emails:')
        for email in emails:
            msg = service.users().messages().get(userId='me', id=email['id']).execute()
            print(f"Subject: {msg['subject']}")
            print(f"From: {msg['from']}")
            print(f"Snippet: {msg['snippet']}")
            print('---')
# Call the fetch_emails() function to test
fetch_emails()

In the code, we define the necessary scopes for Gmail access and import essential libraries. The get_gmail_service() method establishes a connection to the Gmail API and authenticates the user. User credentials are securely stored and retrieved from the token.pickle file. This enables secure and efficient access to the user's Gmail account within the Django application, ensuring an authentication experience.

The fetch_emails() function retrieves the emails from the user's Gmail inbox using the Gmail API methods users().messages().list() and users().messages().get(). It prints the subject, sender, and snippet of each email.

To run the code and fetch emails, please ensure that we have the credentials.json file located in the same directory as the gmail.py file.

Here's an example:

python gmail.py

This will authenticate the user and print out the details of the emails fetched from the user's Gmail inbox.

Conclusion

In conclusion, Python Django provides a seamless and secure way to implement Google authentication and fetch emails within your web application. By Django−allauth and the Google API client library, we can easily enable users to log in using their Google credentials and access their Gmail inbox. This integration opens up a wide range of possibilities for building email−centric applications, such as messaging systems, email analytics, and more.

With Django's robust framework and the power of Google's APIs, we can create feature−rich applications that streamline user authentication and enhance email−related functionalities. Python Django truly simplifies the process of integrating Google authentication and fetching emails from scratch.

Updated on: 25-Jul-2023

290 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements