问题
I'm trying to set up the gmail api to send emails automatically using google's sample code. When trying to send an email, I receive a 401 error.
I've set up quickstart and given it access to my gmail for all purposes. I can access my account through the API for other purposes, such as retrieving labels, but not sending emails. I've tried deleting and remaking my token several times, and I have set SCOPES to include sending emails and that shows up in my google account.
def create_message(sender, to, subject, message_text):
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
return {'raw': base64.urlsafe_b64encode(message.as_bytes())}
with open('token.pickle', 'wb') as token:
creds=pickle.load(token)
service = build('gmail', 'v1', credentials=creds)
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
print(labels)
#this script works up to here
message = service.users().messages().send(userId='me', body=create_message('myemail@gmail.com', 'testemail@gmail.com', 'Test', '')).execute()
print('Message Id: %s' % message['id'])
print(message)
As expected, the labels print correctly, but I receive the following error for trying to send the message:
HttpError: <HttpError 400 when requesting
https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "'raw' RFC822 payload message string or uploading message via /upload/* URL required">
which leads to:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}
来源:https://stackoverflow.com/questions/56225578/gmail-api-throws-401-error-login-required-only-for-sending-emails