'Why does the Gmail API return an "invalid to header" error while my API had been working fine for weeks?

Using the quickstart guide for the Gmail API with Python, I get an 400 error "Invalid to header" when trying to create a draft.

I have been using my little script for a few weeks and it worked perfectly fine to create invoice drafts in bulk, until one day it just stopped working even though I had not modified any code.

This is the error I get:

   1 file(s) copied.
Traceback (most recent call last):
File "quickstart.py", line 223, in <module>
main()
File "quickstart.py", line 207, in main
create_draft(service, 'me', message_body)
File "quickstart.py", line 134, in create_draft
draft = service.users().drafts().create(userId=user_id, body=message).execute()
File "C:\Users\$User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Users\$User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\googleapiclient\http.py", line 842, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/drafts?alt=json returned "Invalid to header">

When I got this error for the first time, I deleted the credentials file and downloaded a new one. But now this solution doesn't seem to work anymore.

Does the credentials.json file expire after some time?



Solution 1:[1]

i got the same error when tried to send email to "@something2" (normal email is something1@something2, you might miss "something1", e.g your email is invalid)

Error does not happens if you put normal email, so you should validate your input.

Solution 2:[2]

Maybe too late but i have fased this httpError 400 recently which i thought would be an authentication or expirated credential/token error.

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://gmail.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "Invalid To header". Details: "[{'message': 'Invalid To header', 'domain': 'global', 'reason': 'invalidArgument'}]">

While testing my script, it was doing fine until it ran into a... "<" that had snuck and find his place at the beginning of my provider's email in a json file which would then be placed in the code into mimeMessage['to'] = recipient_email.

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vova
Solution 2 Alejo Capovilla