这是我第一次使用gmail api。我正在尝试通过服务帐户使用 gmail api。我的程序的目标是仅通过我的电子邮件解析电子邮件并查找某些关键字并将它们与本地数据库进行比较。但是我无法连接到 gmail api。我确实执行了创建服务帐户、下载服务帐户密钥 json 文件并向服务帐户授予域范围委派权限的步骤。我还给出了 https://mail.google.com/ 的范围。我只是想证明我可以连接并且通过执行 getprofile 调用进行身份验证。
const {google} = require('googleapis');
const auth = new google.auth.GoogleAuth({
keyFile: './serviceaccountkey.json',
scopes: ['https://mail.google.com/'],
subject: '[email protected]',
});
const gmail1 = google.gmail({version: 'v1', auth: auth});
async function temp1(){
var cont = gmail1.users.getProfile({userId: "me",})
return cont;
}
console.log(temp1());
这不起作用,因为我返回了前提条件检查失败的错误。
throw new common_1.GaxiosError(`Request failed with status code ${translatedResponse.status}`, opts, translatedResponse);
^
GaxiosError: Precondition check failed.
at Gaxios._request (C:\Users\user\Documents\FunctionAzure\node_modules\gaxios\build\src\gaxios.js:130:23)
我得到的唯一代码是 400,带有前提条件检查失败的消息。
我期望看到 get profile gmail api 调用的输出。我已经阅读了一些内容,我唯一的猜测是我需要使用 JWT 做一些我对此感到困惑的事情。 JWT 和您下载的服务帐户 json 文件是同一个东西吗?我很感激任何人都可以提供的见解,谢谢
根据您的身份验证方式,我认为您应该直接请求公开 'auth' 的 gmail 子模块,即您的代码应该是
// request the gmail module which exposes auth
const gmail = require('@googleapis/gmail')
// provide information for authenticating
const auth = new gmail.auth.GoogleAuth({
keyFile: './serviceaccountkey.json',
scopes: ['https://mail.google.com/'],
subject: '[email protected]',
});
// create an auth client
const authClient = await auth.getClient();
// authenticate to gmail and create a gmail client
const gmail1 = await gmail.gmail({
version: 'v1',
auth: authClient
});
请参阅其文档中的示例此处(查找相应部分 - 或者,您可以通过安装子模块直接调用 API)
基于@NoCommandLine 答案。
您必须在获得 authClient
之后通过主题选项。
// request the gmail module which exposes auth
const gmail = require('@googleapis/gmail')
// provide information for authenticating
const auth = new gmail.auth.GoogleAuth({
keyFile: './serviceaccountkey.json',
scopes: ['https://mail.google.com/']
});
// create an auth client
const authClient = await auth.getClient();
authClient.subject = '[email protected]'; // Set the subject here!
// authenticate to gmail and create a gmail client
const gmail1 = await gmail.gmail({
version: 'v1',
auth: authClient
});