Search code examples
node.jsgmailgoogle-api-js-client

Get the last email of a tag in GAPI


I have the init gmail quickstart, but i want to be able to get the last email of a tag. The code i have is this. And i dont know what i have to do or what functions to use.

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

Solution

  • My understanding of the problem:

    • You want to retrieve the letest email in the specific label using Gmail API.
      • I understood the last email of a tag in GAPI like above.
    • You want to achieve this using googleapis with Node.js.
    • You have already been able to get values from Gmail using Gmail API.

    In this answer, I used the following flow.

    1. Retrieve the email list of the label using the method of Users.messages: list in Gmail API.
    2. Retrieve the email using the retrieved ID with the method of Users.messages: get in Gmail API.

    Sample script:

    In the authorization of this sample script, the quickstart for Node.js is used. Ref Before you use this script, please set the label name to const query = "label:sample";. In this case, "sample" is the label name.

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

    Note:

    • In my environment, the 1st index of res1.data.messages is the latest message. If in your environment, the last index is the latest one, please modify above script.
    • If you want to know how to use above script, you can see the official document.

    References: