【问题标题】:Get the last email of a tag in GAPI获取 GAPI 中标签的最后一封电子邮件
【发布时间】:2020-08-02 16:22:06
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    我对问题的理解:

    • 您想使用 Gmail API 检索特定标签中的最信电子邮件。
      • 我理解the last email of a tag in GAPI 就像上面一样。
    • 您希望使用带有 Node.js 的 googleapis 来实现此目的。
    • 您已经能够使用 Gmail API 从 Gmail 获取值。

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

    1. 使用Users.messages的方法检索标签的电子邮件列表:Gmail API中的列表。
    2. 通过Users.messages的方法使用检索到的ID检索电子邮件:进入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);
        });
      });
    }
    

    注意:

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

    参考资料:

    【讨论】:

    • @PWall 感谢您的回复。我带来的不便表示歉意。不幸的是,来自Doesnt work for me.,我无法了解您当前问题的细节。这是我糟糕的英语水平。我对此深表歉意。为了正确理解它,您能提供它的详细信息吗?因为在我的环境中,我可以确认脚本有效。如果您能合作解决您的问题,我很高兴。
    • @PWall 感谢您的回复。从错误信息来看,我认为您设置的标签没有任何信息。那么请您再次确认标签名称和消息吗?如果可以,请在没有您个人信息的情况下将整个脚本添加到您的问题中。顺便说一句,您已经发布了您的附加信息作为答案。当您添加更多信息时,请将其添加到您的问题中。请删除您作为答案发布的内容。
    猜你喜欢
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 2020-08-04
    相关资源
    最近更新 更多