微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Google API - 使用 nodejs 客户端创建转发地址

如何解决Google API - 使用 nodejs 客户端创建转发地址

在我的 nodejs 项目中,我想以编程方式为 gmail 创建转发地址。为了获得 googleApi 客户端,我这样做:

let oauth2client = new google.auth.OAuth2(
      client_id,client_secret,redirect_uris[0])

我通过像这样从后端生成 auth url 来执行 oauth:

const authUrl = oauth2client.generateAuthUrl({
    access_type: 'offline',scope: ['https://www.googleapis.com/auth/gmail.readonly','https://www.googleapis.com/auth/gmail.settings.sharing'],});

然后将前端重定向到上面的 URL,一旦在我的回调 url 上收到代码,我就会得到令牌 f=like this

const token = await oauth2client.getToken(code);

令牌的响应是这样的:

const tokenRes = {"tokens":{"access_token":"redacted","refresh_token":"redacted","scope":"https://www.googleapis.com/auth/gmail.settings.sharing https://www.googleapis.com/auth/gmail.readonly","token_type":"Bearer","expiry_date":1615396541573},"res":{"config":{"method":"POST","url":"https://oauth2.googleapis.com/token","data":"redacted","headers":{"Content-Type":"application/x-www-form-urlencoded","User-Agent":"google-api-nodejs-client/3.1.2","Accept":"application/json"},"params":{},"body":"redacted","responseType":"json"},"data":{"access_token":"redacted","headers":{"alt-svc":"redacted","cache-control":"no-cache,no-store,max-age=0,must-revalidate","connection":"close","content-encoding":"gzip","content-type":"application/json; charset=utf-8","date":"Wed,10 Mar 2021 16:15:42 GMT","expires":"Mon,01 Jan 1990 00:00:00 GMT","pragma":"no-cache","server":"scaffolding on HTTPServer2","transfer-encoding":"chunked","vary":"Origin,X-Origin,Referer","x-content-type-options":"nosniff","x-frame-options":"SAMEORIGIN","x-xss-protection":"0"},"status":200,"statusText":"OK"}}

然后我将这段代码放在 oauth2client 中,如下所示:

oauth2client.setCredentials(tokenRes.tokens);

(我展示了上面的代码只是为了确认我做的很好)

现在要创建一个转发地址,我正在这样做:

const gmail = google.gmail({
            version: 'v1',auth: oauth2client
        });
const address = { forwardingEmail: 'foo@bar.com' }
const result = await gmail.users.settings.forwardingAddresses.create({userId: 'me',requestBody: address,auth: oauth2client});

这里出现错误

GaxiosError: Access restricted to service accounts that have been delegated domain-wide authority
    at Gaxios.<anonymous> (/Users/vdev/dev/email-forwarding/node_modules/gaxios/build/src/gaxios.js:73:27)
    at Generator.next (<anonymous>)
    at fulfilled (/Users/vdev/dev/email-forwarding/node_modules/gaxios/build/src/gaxios.js:16:58)
    at runMicrotasks (<anonymous>)
    at processticksAndRejections (internal/process/task_queues.js:93:5)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。