Python Django: Google Authentication and Fetching mails from scratch

Python Django is a powerful web framework that simplifies development and enables robust web applications. In this article, we'll explore integrating Google authentication and Gmail email fetching using Django-allauth and the Google API client library.

This guide provides step-by-step implementation of Google OAuth authentication and email retrieval, perfect for building messaging platforms or email-based applications.

Prerequisites and Installation

First, install the required packages ?

pip install django django-allauth google-api-python-client google-auth-oauthlib

Setting Up Google Authentication

Configure Django Settings

Add the required apps to your settings.py file ?

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    
    # Django-allauth
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
]

SITE_ID = 1

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

# Google OAuth Configuration
SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': [
            'profile',
            'email',
            'https://www.googleapis.com/auth/gmail.readonly'
        ],
        'AUTH_PARAMS': {
            'access_type': 'offline',
            'approval_prompt': 'force'
        }
    }
}

# Redirect URLs
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'

URL Configuration

Update your main urls.py to include allauth URLs ?

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('allauth.urls')),
    path('', include('myapp.urls')),  # Your app URLs
]

Creating Views

Create views for handling authentication and email fetching in views.py ?

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from allauth.socialaccount.models import SocialToken
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
import base64

def home(request):
    return render(request, 'home.html')

@login_required
def fetch_emails(request):
    try:
        # Get the user's Google token
        social_token = SocialToken.objects.get(
            account__user=request.user,
            account__provider='google'
        )
        
        # Create credentials object
        credentials = Credentials(
            token=social_token.token,
            refresh_token=social_token.token_secret,
            client_id='your-client-id.googleusercontent.com',
            client_secret='your-client-secret'
        )
        
        # Build Gmail service
        service = build('gmail', 'v1', credentials=credentials)
        
        # Fetch emails
        results = service.users().messages().list(
            userId='me', 
            labelIds=['INBOX'], 
            maxResults=10
        ).execute()
        
        messages = results.get('messages', [])
        emails = []
        
        for message in messages:
            msg = service.users().messages().get(
                userId='me', 
                id=message['id']
            ).execute()
            
            # Extract email details
            headers = msg['payload'].get('headers', [])
            subject = next((h['value'] for h in headers if h['name'] == 'Subject'), 'No Subject')
            sender = next((h['value'] for h in headers if h['name'] == 'From'), 'Unknown Sender')
            snippet = msg.get('snippet', 'No preview available')
            
            emails.append({
                'subject': subject,
                'sender': sender,
                'snippet': snippet
            })
        
        return render(request, 'emails.html', {'emails': emails})
        
    except Exception as e:
        return render(request, 'error.html', {'error': str(e)})

Creating Templates

Base Template

Create templates/base.html ?

<!DOCTYPE html>
<html>
<head>
    <title>Django Google Auth</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="/">Gmail Integration</a>
            <div class="navbar-nav ms-auto">
                {% if user.is_authenticated %}
                    <a class="nav-link" href="{% url 'fetch_emails' %}">My Emails</a>
                    <a class="nav-link" href="{% url 'account_logout' %}">Logout</a>
                {% else %}
                    <a class="nav-link" href="{% url 'account_login' %}">Login</a>
                {% endif %}
            </div>
        </div>
    </nav>
    
    <div class="container mt-4">
        {% block content %}
        {% endblock %}
    </div>
</body>
</html>

Home Template

Create templates/home.html ?

{% extends 'base.html' %}

{% block content %}
<div class="row justify-content-center">
    <div class="col-md-6">
        <div class="card">
            <div class="card-body text-center">
                <h2>Welcome to Gmail Integration</h2>
                {% if user.is_authenticated %}
                    <p>Hello, {{ user.first_name }}!</p>
                    <a href="{% url 'fetch_emails' %}" class="btn btn-primary">View My Emails</a>
                {% else %}
                    <p>Please login with your Google account to access your emails.</p>
                    <a href="{% url 'socialaccount_login' provider='google' %}" class="btn btn-danger">
                        Login with Google
                    </a>
                {% endif %}
            </div>
        </div>
    </div>
</div>
{% endblock %}

Emails Template

Create templates/emails.html ?

{% extends 'base.html' %}

{% block content %}
<h2>Your Recent Emails</h2>

{% if emails %}
    {% for email in emails %}
        <div class="card mb-3">
            <div class="card-body">
                <h5 class="card-title">{{ email.subject }}</h5>
                <h6 class="card-subtitle mb-2 text-muted">From: {{ email.sender }}</h6>
                <p class="card-text">{{ email.snippet }}</p>
            </div>
        </div>
    {% endfor %}
{% else %}
    <div class="alert alert-info">No emails found.</div>
{% endif %}
{% endblock %}

Google Console Setup

To complete the setup, you need to configure OAuth credentials in Google Console ?

  1. Visit the Google Developers Console
  2. Create a new project or select existing one
  3. Enable Gmail API and Google+ API
  4. Go to "Credentials" ? "Create Credentials" ? "OAuth client ID"
  5. Choose "Web application" and add your redirect URIs:
    • http://localhost:8000/accounts/google/login/callback/
    • http://127.0.0.1:8000/accounts/google/login/callback/
  6. Copy the Client ID and Client Secret to Django admin under Sites ? Social applications

Running the Application

Run migrations and start the development server ?

python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver

Visit http://localhost:8000/admin/ to add your Google OAuth credentials under "Social applications".

Security Considerations

For production deployment, ensure you ?

  • Store credentials securely using environment variables
  • Use HTTPS for all OAuth redirects
  • Implement proper error handling and user feedback
  • Add rate limiting for API calls
  • Handle token refresh automatically

Conclusion

Django-allauth provides seamless Google authentication integration, while the Google API client library enables secure Gmail access. This combination allows you to build powerful email-centric applications with proper OAuth authentication and API access management.

Updated on: 2026-03-27T10:00:23+05:30

882 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements