- Access the developer console https://console.developers.google.com
- Create a new project
- 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.
- In APIs and Oauth/Credentials, under Client ID for native application, click download json.
- Run
pip install --upgrade google-api-python-client
- Run the following python code:
from oauth2client.client import flow_from_clientsecrets
CLIENTSECRETS_LOCATION = '/downloaded/json/file/path'
REDIRECT_URI ='copy-from-the-credentials-tab. should look something like: urn:ietf:wg:oauth:2.0:oob'
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))
import logging
auth_uri = flow.step1_get_authorize_url(REDIRECT_URI)
- Browse to the URL given in
auth_uri
- Click accept and copy the code
- Get your credentials using the copied code
credentials = flow.step2_exchange('the-copied-code')
from oauth2client.file import Storage
storage = Storage('/path/to/credentials.txt')
storage.put(credentials)
credentials2 = storage.get()
json = credentials.to_json()
from oauth2client.client import Credentials
credentials2 = Credentials.new_from_json(json)
from apiclient.discovery import build
import httplib2
http = httplib2.Http()
http = credentials.authorize(http)
service = build('gmail', 'v1', http=http)
response = service.users().messages().list(userId='[email protected]').execute()
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
thanks for Help!