You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于收件人筛选:用NodeJS和Gmail API获取最新3封邮件

Fetch Latest 3 Emails for a Specific Recipient with Gmail API (Node.js)

Got it, let's adjust your code to fetch the latest 3 emails sent to a specific recipient. The key changes involve using Gmail API's query filter to target the recipient, increasing the max results, and handling multiple messages instead of just one. Here's the modified code with explanations:

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');

// 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;
  }
  // Replace this with your target recipient's email
  const targetRecipient = 'your-recipient@example.com';
  // Authorize and call our updated email-fetching function
  authorize(JSON.parse(content), (auth) => {
    getLatestEmailsByRecipient(auth, targetRecipient);
  });
});

/**
 * 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 latest 3 emails sent to a specific recipient
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 * @param {string} recipientEmail The email address of the target recipient.
 */
function getLatestEmailsByRecipient(auth, recipientEmail) {
  // Use Gmail API query filter to target messages sent to the recipient
  // maxResults set to 3 to get the latest 3 emails
  gmail.users.messages.list({
    auth: auth,
    userId: 'me',
    maxResults: 3,
    q: `to:${recipientEmail}`,
    format: 'full' // Ensure we get complete header data
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }

    const messages = response.data.messages;
    if (!messages || messages.length === 0) {
      console.log(`No emails found for recipient: ${recipientEmail}`);
      return;
    }

    console.log(`Found ${messages.length} emails for ${recipientEmail}:\n`);

    // Loop through each message ID to fetch full email details
    messages.forEach((msg, index) => {
      gmail.users.messages.get({
        auth: auth,
        userId: 'me',
        id: msg.id,
        format: 'full'
      }, function(err, message) {
        if (err) {
          console.log(`Error fetching message ${index + 1}:`, err);
          return;
        }

        // Extract the recipient (To field) from headers
        const toHeader = message.data.payload.headers.find(header => header.name === 'To');
        const recipient = toHeader ? toHeader.value : 'Unknown Recipient';

        // Parse email content (handles both plain text and multipart emails)
        let emailContent = '';
        try {
          // Check if email is a single part
          if (message.data.payload.body.data) {
            // Gmail uses base64url encoding, not standard base64
            const buff = Buffer.from(message.data.payload.body.data, 'base64url');
            emailContent = buff.toString();
          } 
          // Handle multipart emails (most common)
          else if (message.data.payload.parts) {
            // Find the plain text part of the email
            const textPart = message.data.payload.parts.find(part => part.mimeType === 'text/plain');
            if (textPart && textPart.body.data) {
              const buff = Buffer.from(textPart.body.data, 'base64url');
              emailContent = buff.toString();
            } else {
              emailContent = 'No plain text content found';
            }
          }

          // Log the email details
          console.log(`--- Email ${index + 1} ---`);
          console.log(`Recipient: ${recipient}`);
          console.log(`Content:\n${emailContent}`);
          console.log('------------------------\n');
        } catch (parseErr) {
          console.log(`Error parsing email ${index + 1}:`, parseErr);
        }
      });
    });
  });
}

Key Changes Explained:

  • Recipient Filter: Added the q parameter to users.messages.list with to:${recipientEmail} to only fetch emails sent to your target address.
  • Increased Max Results: Changed maxResults from 1 to 3 to retrieve the latest 3 emails.
  • Multi-Message Handling: Replaced single-message logic with a loop to process all returned messages.
  • Improved Content Parsing: Switched to base64url decoding (Gmail uses this instead of standard base64) and added better support for multipart emails (the most common email format).
  • Full Header Access: Added format: 'full' to ensure we get complete header data (like the To field) for each email.

Just replace your-recipient@example.com with the actual email address you want to target, then run the code as before.

内容的提问来源于stack exchange,提问作者James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:07:20