Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Precondition check failed error using Gmail (GSuite) account #984

Closed
risoms opened this issue Jul 26, 2020 · 3 comments
Closed

Precondition check failed error using Gmail (GSuite) account #984

risoms opened this issue Jul 26, 2020 · 3 comments
Assignees
Labels
api: gmail Issues related to the Gmail API API. type: question Request for information or clarification. Not an issue.

Comments

@risoms
Copy link

risoms commented Jul 26, 2020

python version: 3.7
pip: 9.0.1
os type and version: Linux 2.6.32-954.3.5.lve1.4.77.el6
google-api-python-client: 1.10.0

I'm continuing to get an invalid request error trying to submit an email using this library.
I have already set up a: OAuth 2.0 Client ID, Service Account, and Domain-wide Delegation. Although no emails are being sent, I can see that 400 errors are being produced in the "API's and services" page for the service account.

I've provided the code and traceback below.

import base64
from apiclient import errors
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
from httplib2 import Http
from email.mime.text import MIMEText

def service_account_login():
	credentials = Credentials.from_service_account_file(
		'service-key.json', 
		scopes=['https://www.googleapis.com/auth/gmail.send']
	)
	delegated_credentials = credentials.with_subject('me')
	gmail = build('gmail', 'v1', credentials=delegated_credentials)
	return gmail

def create(from_, subject, text):
	"""Create a message for an email

	Parameters
	----------
	from_ : [type]
		Email address of the sender
	subject : [type]
		 The subject of the email message
	text : [type]
		The text of the email message

	Returns
	-------
	[type]
		An object containing a base64url encoded email object
	"""

	message = MIMEText(text)
	message['from'] = from_
	message['to'] = "someone@<gsuite domain>".com
	message['subject'] = subject

	return {
		'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()
	}

def send(from_, subject, text):
	"""[summary]

	Parameters
	----------
	service : [type]
		Authorized Gmail API service instance
	message : [type]
		Message to be sent

	Returns
	-------
	[type]
		Sent Message
	"""

	try:
		message_ = create(from_=from_, subject=subject, text=text)
		service = service_account_login()
		message = (
			service.users()
			.messages()
			.send(userId='', body=message_)
			.execute()
		)
		print(f"Message Id: {message['id']}")

		return message

	except errors.HttpError as error:
		print(f'An error occurred: {error}')
Traceback (most recent call last):
  File "/home/semeon/Mail.py", line 77, in send
    .send(userId='', body=message_)
  File "/home/semeon/virtualenv/app/3.7/lib/python3.7/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/home/semeon/virtualenv/app/3.7/lib/python3.7/site-packages/googleapiclient/http.py", line 901, in execute
    headers=self.headers,
  File "/home/semeon/virtualenv/app/3.7/lib/python3.7/site-packages/googleapiclient/http.py", line 177, in _retry_request
    resp, content = http.request(uri, method, *args, **kwargs)
  File "/home/semeon/virtualenv/app/3.7/lib/python3.7/site-packages/google_auth_httplib2.py", line 190, in request
    self._request, method, uri, request_headers)
  File "/home/semeon/virtualenv/app/3.7/lib/python3.7/site-packages/google/auth/credentials.py", line 133, in before_request
    self.refresh(request)
  File "/home/semeon/virtualenv/app/3.7/lib/python3.7/site-packages/google/oauth2/service_account.py", line 359, in refresh
    access_token, expiry, _ = _client.jwt_grant(request, self._token_uri, assertion)
  File "/home/semeon/virtualenv/app/3.7/lib/python3.7/site-packages/google/oauth2/_client.py", line 153, in jwt_grant
    response_data = _token_endpoint_request(request, token_uri, body)
  File "/home/semeon/virtualenv/app/3.7/lib/python3.7/site-packages/google/oauth2/_client.py", line 124, in _token_endpoint_request
    _handle_error_response(response_body)
  File "/home/semeon/virtualenv/app/3.7/lib/python3.7/site-packages/google/oauth2/_client.py", line 60, in _handle_error_response
    raise exceptions.RefreshError(error_details, response_body)
google.auth.exceptions.RefreshError: ('invalid_request: Invalid impersonation "sub" field.', '{\n  "error": "invalid_request",\n  "error_description": "Invalid impersonation \\u0026quot;sub\\u0026quot; field."\n}')
@yoshi-automation yoshi-automation added the triage me I really want to be triaged. label Jul 27, 2020
@busunkim96
Copy link
Contributor

Hi,

If you've followed the domain-wide delegation steps I don't think you need to change the subject (delegated_credentials = credentials.with_subject('me'). Could you try removing that line?

@busunkim96 busunkim96 added api: gmail Issues related to the Gmail API API. type: question Request for information or clarification. Not an issue. and removed triage me I really want to be triaged. labels Jul 27, 2020
@risoms
Copy link
Author

risoms commented Jul 28, 2020

I've changed it but I'm getting the following error:

Traceback (most recent call last):
  File "/home/semeon/virtualenv/app/3.7/lib/python3.7/site-packages/googleapiclient/discovery_cache/file_cache.py", line 37, in <module>
    from oauth2client.locked_file import LockedFile
ModuleNotFoundError: No module named 'oauth2client'

During handling of the above exception, another exception occurred

Traceback (most recent call last):
  File "/home/semeon/virtualenv/app/3.7/lib/python3.7/site-packages/googleapiclient/discovery_cache/__init__.py", line 44, in autodetect
    from . import file_cache
  File "/home/semeon/virtualenv/app/3.7/lib/python3.7/site-packages/googleapiclient/discovery_cache/file_cache.py", line 41, in <module>
    "file_cache is unavailable when using oauth2client >= 4.0.0 or google-auth"
ImportError: file_cache is unavailable when using oauth2client >= 4.0.0 or google-auth
An error occurred: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users//messages/send?alt=json returned "Precondition check failed.">

@risoms risoms changed the title invalid_request error using Gmail (GSuite) account Precondition check failed error using Gmail (GSuite) account Jul 30, 2020
@parthea parthea assigned parthea and unassigned parthea Dec 6, 2020
@parthea
Copy link
Contributor

parthea commented Dec 16, 2020

Hi @risoms,
I recently improved support for error_details in #1126 so you may see additional information when you use the latest google-api-python-client which could indicate why the precondition check failed.

I'm going to close this issue due to inactivity. If you're still having trouble, please re-open it with more information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api: gmail Issues related to the Gmail API API. type: question Request for information or clarification. Not an issue.
Projects
None yet
Development

No branches or pull requests

4 participants