要访问GMail API(并模拟通话),我使用的是服务帐户(从Google Cloud Platform创建)。我的json文件看起来像这样
{
"type": "service_account",
"project_id": "[PROJECT-ID]",
"private_key_id": "[KEY-ID]"
"private_key": "-----BEGIN PRIVATE KEY-----\n[PRIVATE-KEY]\n-----END PRIVATE KEY-----\n",
"client_email": "[SERVICE-ACCOUNT-EMAIL]",
"client_id": "[CLIENT-ID]",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/[SERVICE-ACCOUNT-EMAIL]"
}
我还使用oauth2client库来简化操作,但是找不到找到凭据的方法,然后指定范围和委托帐户。
我尝试了
from oauth2client import service_account
self._credentials = service_account.ServiceAccountCredentials.from_json(SERVICE_ACCOUNT_JSON_CONTENT)
self._credentials = self._credentials.create_scoped([u'https://www.googleapis.com/auth/gmail.send'])
self._credentials = self._credentials.create_delegated(MY_USER)
self._client = discovery.build(u'gmail', u'v1', credentials=self._credentials)
但是我收到一个错误消息,因为它期望使用PKCS-8密钥。
我该怎么做? (如果有帮助,我的代码可以在App Engine Flex上运行)
谢谢
答案 0 :(得分:0)
最后,由于现在不赞成使用oauth2client而是推荐使用google-auth,所以我这样做了
from googleapiclient import discovery
from google.oauth2.service_account import Credentials
credentials = Credentials.from_service_account_file(PATH_TO_SERVICE_ACCOUNT_JSON,
scopes=[u'https://www.googleapis.com/auth/gmail.send'])
delegated_credentials = self._credentials.with_subject(MY_USER)
client = discovery.build(u'gmail', u'v1', credentials=delegated_credentials)
而且有效;-)