Получить последний адрес электронной почты тега в GAPI - PullRequest
0 голосов
/ 20 апреля 2020

У меня есть быстрый запуск init gmail, но я хочу получить последнее электронное письмо с тегом. Код у меня есть это. И я не знаю, что мне нужно делать или какие функции использовать.

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

1 Ответ

0 голосов
/ 20 апреля 2020

Мое понимание проблемы:

  • Вы хотите получить последнее письмо с указанным c ярлыком, используя Gmail API.
    • Я понял the last email of a tag in GAPI, как указано выше.
  • Вы хотите добиться этого, используя googleapis с Node.js.
  • Вы уже смогли получить значения из Gmail с помощью Gmail API.

В этом ответе я использовал следующий поток.

  1. Получить список адресов электронной почты с меткой, используя метод Users.messages : список в Gmail API.
  2. Получение электронной почты с использованием полученного идентификатора с помощью метода Users.messages: get in Gmail API.

Пример сценария:

В авторизации этого примера сценария используется быстрый запуск для Node.js. 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);
    });
  });
}

Примечание:

  • В моем окружении 1-й индекс res1.data.messages является последним сообщением. Если в вашей среде последний индекс является самым последним, измените приведенный выше скрипт.
  • Если вы хотите узнать, как использовать вышеуказанный скрипт, вы можете увидеть официальный документ .

Ссылки:

...