I am using service account to list the message in my gmail box, however I am getting below error while calling this API service.users().messages().list(userId='me').execute()
HttpError Traceback (most recent call last)
<ipython-input-44-da1dc3cccc81> in <module>
27
28 apiservice = build('gmail', 'v1', credentials=service_cred)
---> 29 response = apiservice.users().messages().list(userId='me').execute()
~/opt/anaconda3/lib/python3.7/site-packages/googleapiclient/_helpers.py in positional_wrapper(*args, **kwargs)
128 elif positional_parameters_enforcement == POSITIONAL_WARNING:
129 logger.warning(message)
--> 130 return wrapped(*args, **kwargs)
131 return positional_wrapper
132
~/opt/anaconda3/lib/python3.7/site-packages/googleapiclient/http.py in execute(self, http, num_retries)
849 callback(resp)
850 if resp.status >= 300:
--> 851 raise HttpError(resp, content, uri=self.uri)
852 return self.postproc(resp, content)
853
HttpError: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/messages?alt=json returned "Precondition check failed.">
code:
scopes = [
"https://mail.google.com/",
"https://www.googleapis.com/auth/gmail.modify",
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.labels",
"https://www.googleapis.com/auth/gmail.metadata",
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
]
service_cred = service_account.Credentials.from_service_account_info(
credentials, scopes=scopes)
service = build('gmail', 'v1', credentials=service_cred)
response = service.users().messages().list(userId='me').execute()
Precondition failure would typically mean that the destination (facebook, youtube, twitch) was unable to authenticate and resolve the host. This could be caused by a firewall or security restriction on your network, it could also be an issue with the account to which you are trying to pair.
I ran in to this as well when trying to list emails from my personal email. The Google dashboard set me up with service account credentials when enabling the Gmail API, so I assumed that was what I should use.
To make that 400 error go away, I had to add:
delegated_credentials = credentials.with_subject('[email protected]')
See https://developers.google.com/identity/protocols/oauth2/service-account#authorizingrequests.
However, I then got an error that my service account was unauthorized to make requests on behalf of my personal email. And if you're not using G Suite, I don't think there's a way to use a service account on behalf of a user.
So the ultimate solution to my problem was to use the OAuth authentication like in the Python Quickstart.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With