[Answered ]-Get gmail email using django allAuth

2đź‘Ť

It’s old question without views and activity, but for some reason I found it quickly while googling. I think it can be helpful for someone.

First of all: you need to use server-side flow and you need OAuth 2 Clien ID with type “Web Application” (but it depends).
With server-side flow, you have to exchange google’s auth code with access/refresh tokens on your server.

It’s a basic django-allauth conf to do what you want:

SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': [
            'profile',
            'email',
            'https://www.googleapis.com/auth/gmail.readonly',
        ],
        'AUTH_PARAMS': {
            'access_type': 'offline',  # to request refresh_token from Google 
        }
    }
}

Then basic logic to get API service (aka API client):

from allauth.socialaccount.models import SocialToken, SocialApp
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

def get_gmail_service(token: SocialToken):
    # SocialToken.token_secret is a refresh token in case of Google
    assert token.token_secret, 'Can not use SocialToken without refresh token!'

    google_app = SocialApp.objects.filter(provider='google').first()
    assert google_app, 'Must create SocialApp for google provider first!'

    # this is simple example, but you need to use some credentials storage 
    # instead of SocialToken or manage how to sync creads data to SocialToken
    credentials = Credentials(
         token=token.token,
         refresh_token=token.token_secret,
         token_uri='https://oauth2.googleapis.com/token',
         client_id=google_app.client_id,
         client_secret=google_app.secret)

    return build('gmail', 'v1', credentials=credentials)

To test your service:

service = get_gmail_service(SocialToken.objects.first())
try:
    res = service.users().messages().list(userId='me', maxResults=1).execute()
except HttpError as err:
    print('GMAIL ACCESS CHECK ERROR:', err)
else:
    print('GMAIL SUCCESS!')
👤Mark Mishyn

Leave a comment