我想编写一个应用程序来处理我的一些以某种方式标记的 Gmail 电子邮件。
这里的示例代码为我的代码提供了一个起点(我使用 Promise 而不是 async wait 重写了代码):
'use strict';
const path = require('path');
const { google } = require('googleapis');
const { authenticate } = require('@google-cloud/local-auth');
authenticate({
keyfilePath: path.join(__dirname, 'key.json'),
scopes: [
'https://www.googleapis.com/auth/gmail.readonly',
],
}).then(auth => {
google.options({ auth })
gmail.users.messages.list({
userId: "me",
}).then((res) => {
console.log(res.data)
}).catch(err => {
console.log(err)
})
}).catch(err => {
console.log(err);
})
Run Code Online (Sandbox Code Playgroud)
以下是我到目前为止所采取的步骤:
key.jsonGOOGLE_APPLICATION_CREDENTIALS="$(pwd)/key.json" node index.js
Run Code Online (Sandbox Code Playgroud)
这是我收到的错误:
TypeError: Cannot read property 'redirect_uris' of undefined
at authenticate (/home/user/dev/gmail-processor/node_modules/@google-cloud/local-auth/build/src/index.js:46:15)
at …Run Code Online (Sandbox Code Playgroud) javascript node.js google-cloud-platform gmail-api google-auth-library-nodejs
我正在使用自定义服务帐户(使用--service-account部署命令中的参数)。该服务帐户已启用域范围委派,并且安装在 G Apps 管理面板中。
我尝试了这段代码:
app.get('/test', async (req, res) => {
const auth = new google.auth.GoogleAuth()
const gmailClient = google.gmail({ version: 'v1' })
const { data } = await gmailClient.users.labels.list({ auth, userId: 'user@domain.com' })
return res.json(data).end()
})
Run Code Online (Sandbox Code Playgroud)
如果我在我的计算机上运行它(将GOOGLE_APPLICATION_CREDENTIALS环境变量设置为分配给 Cloud Run 服务的同一服务帐户的路径),它就可以工作,但是当它在 Cloud Run 中运行时,我会收到以下响应:
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Bad Request",
"reason" : "failedPrecondition"
} ],
"message" : "Bad Request"
}
Run Code Online (Sandbox Code Playgroud)
我看到了针对同一问题的解决方案,但它适用于 Python,我不知道如何使用 Node 库复制该行为。
node.js service-accounts google-auth-library-nodejs google-cloud-run