运行代码时出现此错误:
google.auth.exceptions.RefreshError: ('unauthorized_client: 客户端未授权使用此方法检索访问令牌,或客户端未授权任何请求的范围。', {'error': 'unauthorized_client', 'error_description': '客户端未授权使用此方法检索访问令牌,或者客户端未授权任何请求的范围。'})
这是代码:
from __future__ import print_function
from googleapiclient import discovery, errors
from oauth2client import file, client, tools
from google.oauth2 import service_account
from email.mime.text import MIMEText
import base64
SERVICE_ACCOUNT_FILE = 'keys.json'
SCOPES = [' https://www.googleapis.com/auth/gmail.send']
# The user we want to "impersonate"
USER_EMAIL = "myName@myDomain.com"
def validationService():
# Set the crendentials
credentials = service_account.Credentials. \
from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# Delegate the credentials to the user you want to impersonate
delegated_credentials = credentials.with_subject(USER_EMAIL)
service = discovery.build('gmail', 'v1', credentials=delegated_credentials)
return service
def send_message(service):
gmail_from = 'myName@myDomain.com'
gmail_to = 'anotherName@gmail.com'
gmail_subject = 'Hello World'
gmail_content = 'test test'
message = MIMEText(gmail_content)
message['to'] = gmail_to
message['from'] = gmail_from
message['subject'] = gmail_subject
raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
body = {'raw': raw}
try:
message = (service.users().messages().send(userId='me', body=body)
.execute())
print('your message has been sent')
return message
except errors.HttpError as error:
print('An error occurred: %s' % error)
send_message(validationService())
我不明白我的电子邮件地址“gmail_from”在代码中的哪个位置连接到我的电子邮件地址。除此之外,我还可以在 gmail 中访问我的 IDE:

我还在谷歌控制台中创建了 OAuth 2.0 客户端 ID 凭据和服务帐户凭据,但我并不真正了解如何/在何处使用这些凭据。
我错过了什么?
在谷歌网站上:https ://developers.google.com/identity/protocols/oauth2/service-account#error-codes我发现我需要“在管理控制台的域范围委派页面中,删除客户端,并使用数字 ID 重新添加它。” 但我不明白该怎么做,也不知道这有什么帮助。