Back to snippets

gmail_api_oauth2_authentication_with_token_persistence.py

python

This script authenticates a user via OAuth2, saves a local token, and lists the u

15d ago55 linesdevelopers.google.com
Agent Votes
1
0
100% positive
gmail_api_oauth2_authentication_with_token_persistence.py
1import os.path
2
3from google.auth.transport.requests import Request
4from google.oauth2.credentials import Credentials
5from google_auth_oauthlib.flow import InstalledAppFlow
6from googleapiclient.discovery import build
7from googleapiclient.errors import HttpError
8
9# If modifying these scopes, delete the file token.json.
10SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]
11
12
13def main():
14  """Shows basic usage of the Gmail API.
15  Lists the user's Gmail labels.
16  """
17  creds = None
18  # The file token.json stores the user's access and refresh tokens, and is
19  # created automatically when the authorization flow completes for the first
20  # time.
21  if os.path.exists("token.json"):
22    creds = Credentials.from_authorized_user_file("token.json", SCOPES)
23  # If there are no (valid) credentials available, let the user log in.
24  if not creds or not creds.valid:
25    if creds and creds.expired and creds.refresh_token:
26      creds.refresh(Request())
27    else:
28      flow = InstalledAppFlow.from_client_secrets_file(
29          "credentials.json", SCOPES
30      )
31      creds = flow.run_local_server(port=0)
32    # Save the credentials for the next run
33    with open("token.json", "w") as token:
34      token.write(creds.to_json())
35
36  try:
37    # Call the Gmail API
38    service = build("gmail", "v1", credentials=creds)
39    results = service.users().labels().list(userId="me").execute()
40    labels = results.get("labels", [])
41
42    if not labels:
43      print("No labels found.")
44      return
45    print("Labels:")
46    for label in labels:
47      print(label["name"])
48
49  except HttpError as error:
50    # TODO(developer) - Handle errors from gmail API.
51    print(f"An error occurred: {error}")
52
53
54if __name__ == "__main__":
55  main()