How to use google gmail api to send email with service account?

import asyncssh, aiohttp, asyncio, jwt, uvloop, json, pathlib, builtins, time

async def gcloud():
serviceAccount = json.loads(pathlib.Path(file).parent.joinpath(‘gcloud.json’).read_text())
async with aiohttp.ClientSession() as client:
now = builtins.int(time.time())
async with client.post(‘https://oauth2.googleapis.com/token’, data={‘grant_type’:‘urn:ietf:params:oauth:grant-type:jwt-bearer’, ‘assertion’:jwt.encode({‘iss’:serviceAccount.get(‘client_email’), ‘scope’:‘https://www.googleapis.com/auth/gmail.readonly’, ‘aud’:‘https://oauth2.googleapis.com/token’, ‘iat’:now, ‘exp’:now + 3600}, serviceAccount.get(‘private_key’), algorithm=‘RS256’)}) as token:
accessToken = (await token.json()).get(‘access_token’)
async with client.get(‘https://gmail.googleapis.com/gmail/v1/users/(PII Removed by Staff)@gmail.com/profile’, headers={‘authorization’:'Bearer ’ + accessToken}) as _:print(await _.json())

uvloop.run(gcloud())

this is my source code

and I get {‘error’: {‘code’: 400, ‘message’: ‘Precondition check failed.’, ‘errors’: [{‘message’: ‘Precondition check failed.’, ‘domain’: ‘global’, ‘reason’: ‘failedPrecondition’}], ‘status’: ‘FAILED_PRECONDITION’}} what is wrong?

also, https://console.cloud.google.com/auth/scopes?hl=en&project= what is data access? Do I need to provide Demo video: how will the scopes will be used? to use the gmail api to send email?

I’m just guessing, but only licensed users can send email, so you probably have to impersonate a real user to send the email.

Ah, you’re using this on a consumer account. Still, impersonation is probably the answer.

No, I don’t know how to fix your code. :slight_smile:

what is impersonation?