【问题标题】:"unauthorized_client" error when using google API to send an email使用 google API 发送电子邮件时出现“unauthorized_client”错误
【发布时间】:2021-10-18 18:05:52
【问题描述】:

运行代码时出现此错误:

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:

我还在 google 控制台中创建了 OAuth 2.0 客户端 ID 凭据和服务帐户凭据,但我并不真正了解如何/在何处使用这些凭据。

我错过了什么?

在 google 网站上:https://developers.google.com/identity/protocols/oauth2/service-account#error-codes 我发现我需要“在管理控制台的域范围委派页面中,删除客户端,然后使用数字 ID 重新添加它。”但我不明白该怎么做,也不知道这有什么帮助。

【问题讨论】:

    标签: python email google-api


    【解决方案1】:

    范围内多了一个空格:

    SCOPES = [' https://www.googleapis.com/auth/gmail.send']
               ^ here
    

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    • 谢谢,我已经修复了,但还是出现同样的错误...
    猜你喜欢
    • 2016-05-02
    • 2013-11-24
    • 2014-09-24
    • 2012-04-16
    • 2014-06-07
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    相关资源
    最近更新 更多