【问题标题】:Adding Users Email to read specific email from their inbox using Gmail API添加用户电子邮件以使用 Gmail API 从收件箱中读取特定电子邮件
【发布时间】:2021-09-24 07:03:45
【问题描述】:

我有一个要求,我想从我的应用程序用户的收件箱中阅读特定的电子邮件。我在谷歌控制台中创建了一个项目并添加了 Gmail API。现在我可以使用它阅读我自己的电子邮件了。但我不知道如何验证我的用户并且能够从我的应用程序中读取他们的电子邮件。我的应用程序在 Nodejs 中。

对于我想要为另一个用户执行的每个操作:

API 返回一个错误:错误:Delegation denied for

fs.readFile('credentials.json', (err, content) => {
    if (err) return console.log('Error loading client secret file:', err);
    // Authorize a client with credentials, then call the Gmail API.
    authorize(JSON.parse(content), getRecentEmail);
  });

function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getNewToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

function getRecentEmail(auth) {
   
  // Only get the recent email - 'maxResults' parameter
  gmail.users.messages.list({auth: auth, userId: 'me',  maxResults: 10,}, function(err, response) {
      if (err) {
          console.log('The API returned an error: ' + err);
          return;
      }
    
    // Get the message id which we will need to retreive tha actual message next.
    var message_id = response['data']['messages'][0]['id'];
    // Retreive the actual message using the message id
    //https://gmail.googleapis.com/gmail/v1/users/{userId}/settings/delegates
    gmail.users.messages.get({auth: auth, userId: 'me', 'id': message_id}, function(err, response) {
        if (err) {
            console.log('The API returned an error: ' + err);
            return;
        }
       
       console.log(response['data']);
      let message_raw = response['data']['payload']['parts'][0].body.data;

     let data = message_raw;  
    let buff = new Buffer(data, 'base64');  
    let text = buff.toString();

    });
  });
}

如果我在 UserId 中添加任何其他邮件 ID,我会收到错误消息。“API 返回错误:错误:Delegation denied for”

请帮助我或建议我是否可以使用其他方法来实现这一目标。

【问题讨论】:

  • 请编辑您的问题并包含您的代码
  • 您现在可以复习吗

标签: node.js google-cloud-platform gmail-api


【解决方案1】:

当您授权您的应用程序时,它被授权给同意您访问的用户。如果您想访问其他用户的数据,则需要将您的应用程序授权为该用户。

除非您创建多个授权连接,否则您不能被授权一次访问多个用户的数据。

如果您收到 API 返回错误:错误:委派被拒绝,因为它让我认为您正在尝试使用服务帐户执行此操作。如果您是,那么您需要在 Google 工作区帐户中设置服务帐户,并授予它代表每个用户访问数据的访问权限。然后,您可以委托您的服务帐户访问该用户数据。

【讨论】:

  • 我能否以某种方式为注册我的应用程序的新用户添加授权以阅读他们的电子邮件。
  • 如果您使用正常的示例代码,您的问题在于 TOKEN_PATH 它的单个用户,您需要修复它,以便为每个授权您的应用程序的用户创建一个新的令牌文件。
  • 是的,我就是这么想的。我需要将 URL 发送给用户,当他们允许访问时,我们将生成一个令牌,但我没有得到任何参考来实现这一点。您能否参考有关此巨大帮助的任何链接或文章。谢谢你
  • 对不起,这里有任何 node.js 通常用于后端系统,换句话说,我不会用它来以这种方式授权用户。用户将通过 Web 应用程序获得授权,然后将刷新令牌及其用户 ID 存储在数据库中,然后 node.js 将从中加载。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-24
  • 1970-01-01
  • 2016-04-20
  • 2015-04-29
  • 2015-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多