Google api HttpError 400在用户()期间先决条件检查失败。消息()。使用服务帐户列出Gmail API调用

Google api HttpError 400在用户()期间先决条件检查失败。消息()。使用服务帐户列出Gmail API调用,google-api,gmail-api,Google Api,Gmail Api,我正在使用服务帐户在我的gmail邮箱中列出消息,但是在调用此APIservice.users().messages().list(userId='me').execute()时出现以下错误 我在尝试列出我个人电子邮件中的电子邮件时也遇到了这个问题。在启用Gmail API时,Google dashboard为我设置了服务帐户凭据,因此我认为这是我应该使用的 为了消除400错误,我必须补充: delegated_credentials = credentials.with_subject('my

我正在使用服务帐户在我的gmail邮箱中列出消息,但是在调用此API
service.users().messages().list(userId='me').execute()时出现以下错误


我在尝试列出我个人电子邮件中的电子邮件时也遇到了这个问题。在启用Gmail API时,Google dashboard为我设置了服务帐户凭据,因此我认为这是我应该使用的

为了消除400错误,我必须补充:

delegated_credentials = credentials.with_subject('my-email@gmail.com')

然而,我随后得到一个错误,我的服务帐户未经授权代表我的个人电子邮件发出请求。如果您没有使用G套件,我认为没有办法代表用户使用服务帐户


因此,我的问题的最终解决方案是使用OAuth身份验证,如中所示。

非常感谢您花时间回复。是的,您使用
和_subject
方法模拟用户帐户解决了问题。我在他们的文档中发现了这一点,但并不容易找到
如果您不使用G Suite,我认为没有办法代表用户使用服务帐户。
我想我是通过艰苦的方式学到这一点的。我不知道他们为什么不在任何地方提到这一点。
scopes = [
    "https://mail.google.com/",
    "https://www.googleapis.com/auth/gmail.modify",
    "https://www.googleapis.com/auth/gmail.readonly",
    "https://www.googleapis.com/auth/gmail.labels",
    "https://www.googleapis.com/auth/gmail.metadata",
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile',
]

service_cred = service_account.Credentials.from_service_account_info(
                credentials, scopes=scopes)

service = build('gmail', 'v1', credentials=service_cred)
response = service.users().messages().list(userId='me').execute()
delegated_credentials = credentials.with_subject('my-email@gmail.com')