0

I'm trying to work on my home project where I contact Google services like Gmail, Sheets, Drive. Services that are not Google Cloud per se.

I've implemented GmailApi quickstart guide for python, but when I try to run I've got error about:

Traceback (most recent call last):
 File "c:\Users48513円\A-i-tomations\Accounting\accounting-scripts\gmail_service.py", line 25, in <module>
 test(creds)
 File "c:\Users48513円\A-i-tomations\Accounting\accounting-scripts\gmail_service.py", line 13, in test
 results = service.users().labels().list(userId="me").execute()
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 File "C:\Users48513円\A-i-tomations\Accounting\accounting-scripts\Lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
 return wrapped(*args, **kwargs)
 ^^^^^^^^^^^^^^^^^^^^^^^^
 File "C:\Users48513円\A-i-tomations\Accounting\accounting-scripts\Lib\site-packages\googleapiclient\http.py", line 923, in execute
 resp, content = _retry_request(
 ^^^^^^^^^^^^^^^
 File "C:\Users48513円\A-i-tomations\Accounting\accounting-scripts\Lib\site-packages\googleapiclient\http.py", line 191, in _retry_request
 resp, content = http.request(uri, method, *args, **kwargs)
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 File "C:\Users48513円\A-i-tomations\Accounting\accounting-scripts\Lib\site-packages\google_auth_httplib2.py", line 209, in request
 self.credentials.before_request(self._request, method, uri, request_headers)
 File "C:\Users48513円\A-i-tomations\Accounting\accounting-scripts\Lib\site-packages\google\auth\credentials.py", line 239, in before_request
 self._blocking_refresh(request)
 File "C:\Users48513円\A-i-tomations\Accounting\accounting-scripts\Lib\site-packages\google\auth\credentials.py", line 202, in _blocking_refresh
 self.refresh(request)
 File "C:\Users48513円\A-i-tomations\Accounting\accounting-scripts\Lib\site-packages\google\oauth2\credentials.py", line 409, in refresh
 ) = reauth.refresh_grant(
 ^^^^^^^^^^^^^^^^^^^^^
 File "C:\Users48513円\A-i-tomations\Accounting\accounting-scripts\Lib\site-packages\google\oauth2\reauth.py", line 349, in refresh_grant
 raise exceptions.RefreshError(
google.auth.exceptions.RefreshError: Reauthentication is needed. Please run `gcloud auth application-default login` to reauthenticate.

But first of all I assume it should not use ADC just use OAuth authentication. With credentials from credentials.json.

Here is the code I used to retrieve credentials:

CLIENTSECRETS_LOCATION = './credentials/credentials.json'
TOKEN_LOCATION = './credentials/token.json'
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
def readCredentials():
 creds = None
 # The file token.json stores the user's access and refresh tokens, and is
 # created automatically when the authorization flow completes for the first
 # time.
 if os.path.exists(TOKEN_LOCATION):
 print("Loading existing credentials from token.json")
 creds = Credentials.from_authorized_user_file(TOKEN_LOCATION, SCOPES)
 # If there are no (valid) credentials available, let the user log in.
 print("Checking credentials validity...")
 if not creds or not creds.valid:
 print("Credentials are not valid or expired.")
 if creds and creds.expired and creds.refresh_token: 
 print("Refreshing expired credentials...")
 creds.refresh(Request())
 else:
 print("No valid credentials available, initiating login flow.")
 flow = InstalledAppFlow.from_client_secrets_file(CLIENTSECRETS_LOCATION, SCOPES)
 creds = flow.run_local_server(port=8080)
 # Save the credentials for the next run
 with open(TOKEN_LOCATION, "w") as token:
 token.write(creds.to_json())

And the code invoking gmail API:

def test(creds: Credentials):
 # Call the Gmail API
 service: Resource = build("gmail", "v1", credentials=creds)
 results = service.users().labels().list(userId="me").execute()
 labels = results.get("labels", [])
 if not labels:
 print("No labels found.")
 return
 print("Labels:")
 for label in labels:
 print(label["name"])
if __name__ == "__main__":
 creds = readCredentials()
 test(creds)

I tried to go with the error message and tried to perform gcloud auth application-default login with my personal account not companies managed, but then I've got this error:

Traceback (most recent call last):
 File "c:\Users48513円\A-i-tomations\Accounting\accounting-scripts\gmail_service.py", line 25, in <module>
 test(creds)
 File "c:\Users48513円\A-i-tomations\Accounting\accounting-scripts\gmail_service.py", line 13, in test
 results = service.users().labels().list(userId="me").execute()
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 File "C:\Users48513円\A-i-tomations\Accounting\accounting-scripts\Lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
 return wrapped(*args, **kwargs)
 ^^^^^^^^^^^^^^^^^^^^^^^^
 File "C:\Users48513円\A-i-tomations\Accounting\accounting-scripts\Lib\site-packages\googleapiclient\http.py", line 938, in execute
 raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://gmail.googleapis.com/gmail/v1/users/me/labels?alt=json returned "Request had insufficient authentication scopes.". Details: "[{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}]">
asked Aug 20 at 13:05
2
  • 1
    You don't return creds at the end of readCredentials Commented Aug 20 at 14:47
  • Oh man, that's why types are important hahahaha Commented Aug 20 at 16:02

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.