在 GAPI 中获取标签的最后一封电子邮件

Get the last email of a tag in GAPI

我有 init gmail quickstart,但我希望能够获取标签的最后一封电子邮件。 我的代码是这样的。而且我不知道我必须做什么或使用什么功能。

const readline = require('readline');
const {google} = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
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), listLabels);
});

/**
* 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) {
 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);
 });
}```

我对问题的理解:

  • 您想使用 Gmail API 检索特定标签中最短的电子邮件。
    • 我明白了the last email of a tag in GAPI如上。
  • 您想使用带有 Node.js 的 googleapis 来实现此目的。
  • 您已经能够使用 Gmail 从 Gmail 获取值 API。

在这个回答中,我使用了以下流程。

  1. 使用Users.messages方法检索标签的邮件列表:Gmail中的列表API。
  2. 使用 Users.messages 的方法使用检索到的 ID 检索电子邮件:进入 Gmail API。

示例脚本:

在这个示例脚本的授权中,使用了Node.js的quickstart。 Ref 在使用此脚本之前,请将标签名称设置为 const query = "label:sample";。在本例中,"sample" 是标签名称。

const fs = require("fs");
const readline = require("readline");
const { google } = require("googleapis");

// If modifying these scopes, delete credentials.json.
const SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"];
const TOKEN_PATH = "token.json";

// Load client secrets from a local file.
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 Google Sheets API.
  authorize(JSON.parse(content), listLabels);
});

/**
 * 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) {
  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);
  });
}

/**
 * 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 for the authorized client.
 */
function getNewToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: "offline",
    scope: SCOPES,
  });
  console.log("Authorize this app by visiting this url:", authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question("Enter the code from that page here: ", (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return callback(err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log("Token stored to", TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

function listLabels(auth) {
  const userId = "me";
  const query = "label:sample";  // Please set the label name. In this case, "sample" is the label name.

  const gmail = google.gmail({ version: "v1", auth });
  gmail.users.messages.list({ userId: userId, q: query }, (err1, res1) => {
    if (err1) {
      console.log(err1);
      return;
    }
    const id = res1.data.messages[0].id;
    gmail.users.messages.get({ userId: userId, id: id }, (err2, res2) => {
      if (err2) {
        console.log(err2);
        return;
      }
      console.log(res2.data);
    });
  });
}

注:

  • 在我的环境中,res1.data.messages 的第一个索引是最新消息。如果在您的环境中,最后一个索引是最新的,请修改上面的脚本。
  • 如果你想知道如何使用上面的脚本,你可以看the official document.

参考文献: