Skip to content

Instantly share code, notes, and snippets.

@chocobn69
Forked from olgakogan/gmail_api.md
Last active October 18, 2022 10:46
Show Gist options
  • Save chocobn69/33ec7f954f50e83346b1573f4b7ae9fb to your computer and use it in GitHub Desktop.
Save chocobn69/33ec7f954f50e83346b1573f4b7ae9fb to your computer and use it in GitHub Desktop.
Manually get OAuth credentials to access your gmail account via API

Basic setup

  1. Access the developer console https://console.developers.google.com
  2. Create a new project
  3. In APIs and Oauth section:
    a. In APIs section - enable gmail api
    b. In Credentials section -
    1. Click Create new client ID
    2. Fill email and project name
    3. Save
    4. Choose Installed application with type other
    5. You should get credentials with the title Client ID for native application.

Getting your credentials

  1. In APIs and Oauth/Credentials, under Client ID for native application, click download json.
  2. Run pip install --upgrade google-api-python-client
  3. Run the following python code:
from oauth2client.client import flow_from_clientsecrets

CLIENTSECRETS_LOCATION = '/downloaded/json/file/path'
SCOPES = [
     ## Choose the scopes relevant for you. Note that the last two are potentially harful.
     'https://www.googleapis.com/auth/gmail.readonly',
     'https://www.googleapis.com/auth/userinfo.email',
     'https://www.googleapis.com/auth/userinfo.profile',
     'https://mail.google.com/',
     'https://www.googleapis.com/auth/gmail.modify',
     'https://www.googleapis.com/auth/gmail.compose',
     ]

flow = flow_from_clientsecrets(CLIENTSECRETS_LOCATION, ' '.join(SCOPES), redirect_uri="http://CHANGEME")
auth_uri = flow.step1_get_authorize_url()
print(auth_uri)
  1. Browse to the URL given in auth_uri
  2. Click accept and copy the code
  3. Get your credentials using the copied code credentials = flow.step2_exchange('the-copied-code')

Saving the credentials

Serializing to file

from oauth2client.file import Storage
storage = Storage('/path/to/credentials.txt')
storage.put(credentials)
credentials2 = storage.get()

Serializing to json

json = credentials.to_json()
from oauth2client.client import Credentials
credentials2 = Credentials.new_from_json(json)

Getting the serivce using the credentials

from apiclient.discovery import build
import httplib2
http = httplib2.Http()
http = credentials.authorize(http)
service = build('gmail', 'v1', http=http)

Running a sample API request

response = service.users().messages().list(userId='the-mail-that-gave-authorization@gmail.com').execute()

The article is based on:

https://developers.google.com/gmail/api/auth/web-server
https://developers.google.com/api-client-library/python/guide/aaa_oauth
https://developers.google.com/api-client-library/python/apis/gmail/v1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment