【问题标题】:NodeJS & Gmail API - Access last 3 emails based on "To:" recipientNodeJS 和 Gmail API - 根据“收件人:”收件人访问最后 3 封电子邮件
【发布时间】:2020-01-11 04:40:05
【问题描述】:

我目前正在使用 NodeJS 和 Gmail API 来访问我的 gmail 帐户并返回我收到的 last 电子邮件,这显然只是使用此代码的 1 封电子邮件:(这是此处示例的略微修改版本:https://www.codediesel.com/nodejs/how-to-access-gmail-using-nodejs-and-the-gmail-api/

var fs = require('fs');
var readline = require('readline');
var {google} = require('googleapis');

// If modifying these scopes, delete your previously saved credentials
// at TOKEN_DIR/gmail-nodejs.json
var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];

// Change token directory to your system preference
var TOKEN_DIR = ('./');
var TOKEN_PATH = TOKEN_DIR + 'gmail-nodejs.json';

var gmail = google.gmail('v1');
//exports.confirmationEmailFinal;

// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }
  // Authorize a client with the loaded credentials, then call the
  // Gmail API.
  authorize(JSON.parse(content), getRecentEmail);

});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
    var clientSecret = credentials.installed.client_secret;
    var clientId = credentials.installed.client_id;
    var redirectUrl = credentials.installed.redirect_uris[0];

    var OAuth2 = google.auth.OAuth2;

    var oauth2Client = new OAuth2(clientId, clientSecret,  redirectUrl);

    // Check if we have previously stored a token.
    fs.readFile(TOKEN_PATH, function(err, token) {
      if (err) {
        getNewToken(oauth2Client, callback);
      } else {
        oauth2Client.credentials = JSON.parse(token);
        callback(oauth2Client);
      }
    });
}

/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback to call with the authorized
*     client.
*/
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({access_type: 'offline', scope: SCOPES});
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
* Store token to disk be used in later program executions.
*
* @param {Object} token The token to store to disk.
*/
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFileSync(TOKEN_PATH, JSON.stringify(token));
  console.log('Token stored to ' + TOKEN_PATH);
}

/**
* Lists the labels in the user's account.
*
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/

function listLabels(auth) {
  gmail.users.labels.list({auth: auth, userId: 'me',}, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }

    var labels = response.data.labels;

    if (labels.length == 0) {
      console.log('No labels found.');
    } else {
      console.log('Labels:');
      for (var i = 0; i < labels.length; i++) {
        var label = labels[i];
        console.log('%s', label.name);
      }
    }
  });

}

/**
* Get the recent email from your Gmail account
*
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function getRecentEmail(auth) {
    // Only get the recent email - 'maxResults' parameter
    gmail.users.messages.list({auth: auth, userId: 'me', maxResults: 1,}, 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
      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;
          }

          // Access the email body content, like this...
          try {
            const message_raw = response.data.payload.body.data;

            data = message_raw;
            buff = new Buffer.from(data, 'base64');
            text = buff.toString();
            console.log(text);
          }
          catch (err){
            const message_raw = response.data.payload.parts[0].body.data;
            console.log('error');

            data = message_raw;
            buff = new Buffer.from(data, 'base64');
            text = buff.toString();
            console.log(text);
          }

      });
    });
}

虽然这工作得非常好,但我希望根据电子邮件的“TO:”收件人找到 3 封最新的电子邮件(不仅仅是 1 封),我目前已将其存储为 email 变量。

任何帮助将不胜感激!

【问题讨论】:

  • gmail.users.messages.list({auth: auth, userId: 'me', maxResults: 1,} 你试过把 1 改大一点吗?
  • @DaImTo 是的,我有,但不幸的是,我没有收到最新的 3 封电子邮件...
  • 我的 node.js 能力有限,但你需要循环它应该返回的结果不止一个。
  • var message_id = response['data']['messages'][0]['id']; 返回最新消息的 ID。就您而言,您还对response['data']['messages'][1]['id']response['data']['messages'][2]['id'] 感兴趣。因此,除了按照 Dalm To 的建议将 maxResults 更改为 3 之外,您还应该实现一个循环,该循环遍历数组 messages 的所需元素数量,获取它们的 ID 并检索每个消息。

标签: node.js email google-api gmail gmail-api


【解决方案1】:

看看这里:https://developers.google.com/gmail/api/guides/filtering

您可以使用 messages.list 搜索或过滤文件和 线程列表方法。这些方法接受 q 参数 支持与 Gmail 网络界面相同的advanced search syntax

【讨论】:

    【解决方案2】:

    通过q 属性使用filters

    const email = 'myEmail@example.com';
    gmail.users.messages.list({
     auth: auth, 
     userId: 'me', 
     maxResults: 1,
     q: `to:${email}`
    }
    

    除了to:address,您还可以使用所有其他搜索/过滤参数,例如is:unread 等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-19
      • 2021-04-19
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 2016-04-05
      相关资源
      最近更新 更多