Hey Yall, im a student whose totally new to GCP, working on a startup idea i have and I am trying to figure out the correct way to access my teams Gmails to help us develop our own custom KPI tracking. I have a project with a service account and service account key. I am trying to use the service account to impersonate me and my team and digest their emails so I can send them to S3. Below is the python code I am using to test everything out
def get_google_credentials():
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.json"):
creds = Credentials.from_authorized_user_file("token.json", SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
"creds.json", SCOPES
)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open("token.json", "w") as token:
token.write(creds.to_json())
return creds
def get_credential(user):
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = credentials.with_subject(user)
return delegated_credentials
def get_gmail_users(creds):
admin_service = build("admin", "directory_v1", credentials=creds)
google_users = admin_service.users().list(customer="my_customer", orderBy="email").execute().get('users', [])
return google_users
def get_gmail_threads_by_user(user_id, creds):
gmail_service = build("gmail", "v1", credentials=creds)
emails = gmail_service.users().messages().list(userId=user_id).execute().get('messages', [])
return emails
Here is there error I get everytime I run the code,
I have looked at 7 different stackoverflow posts to try and figure out where I am going wrong but none of their solutions worked for me.
https://stackoverflow.com/questions/72580300/google-api-call-using-service-account-returns-400-inval...