使用Node.js的Gmail API推送通知

阿比吉特

我正在使用Nodejs和Gmail API制作一个Web应用程序,该应用程序通知我有关以特定标签接收的电子邮件的信息。

经过一番研究,我找到了本指南:推送通知| Gmail API

但我停下来,因为我不明白以后做什么这个

watch()功能可以正常工作,并给我正确的响应。

这是我的完整代码(授权部分摘自Gmail API的Nodejs快速入门指南):

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

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly', "https://www.googleapis.com/auth/pubsub"];
// 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), (auth) => {
        listUnreadMsgs(auth), watchMyLabel(auth)
    });
});

/**
 * 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 console.error('Error retrieving access token', 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);
        });
    });
}
/**
 * Lists the labels in the user's account.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
async function listUnreadMsgs(auth) {
    var gmail = google.gmail({
        auth: auth,
        version: 'v1'
    });

    gmail.users.history.list({
        userId: "me",
        startHistoryId: 2982217,
        labelId: 'Label_8061975816208384485'
    }, async function (err, results) {
        // https://developers.google.com/gmail/api/v1/reference/users/history/list#response
        if (err) return console.log(err);
        const latest = await results.data.history[results.data.history.length - 1].messages;
        gmail.users.messages.get({
            userId: 'me',
            id: latest[latest.length - 1].id
        }, (err, res) => {
            if (res.data.labelIds.includes('UNREAD')) {
                console.log(res.data.snippet);
            } else {
                console.log('No unread messages here!');
            }
        });

    });
}

/**
 * Lists the labels in the user's account.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
async function watchMyLabel(auth) {
    const gmail = google.gmail({
        version: 'v1',
        auth
    });
    const res = await gmail.users.watch({
        userId: 'me',
        requestBody: {
            labelIds: ['Label_8061975816208384485', 'UNREAD'],
            labelFilterAction: "include",
            topicName: 'projects/quickstart-1593237046786/topics/notifications'
        }
    });
}

这是输出:

和这里

接下来做什么?

TL; DR

  • 我正在使用带有Nodejs的Gmail API制作一个推送通知系统。
  • 我不明白,以后该怎么办这个
  • 我希望console.log实时更改邮箱中的更改,而无需重新启动nodejs应用程序。

谢谢。请帮助=)。

编辑:我对webhooks没有事先的了解,所以如果有人能确切解释我接下来要做什么,那将非常好。

阿比吉特

事实证明,下一步是使用Google Cloud Pub / Sub API:使用Pull接收消息

确保适当的授权和用户访问权限。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用Go通过GCP发布/订阅设置Gmail推送通知

用于在Node.js中发送邮件的Gmail API

使用node.js和google-api获取Gmail收件箱

尝试使用Gmail的Node.js API修改标签时出现“错误,未指定标签添加或删除错误”

如何使用One Signal + PHP + Server API发送推送通知?

无法过滤Gmail API推送通知

如何在Node JS中使用Amazon SNS将VoIP推送通知发送到iOS设备

使用PHP的Gmail推送通知

SNS使用Node.js推送带有图像的通知吗?

如何在Node.js中使用Gmail API发送带有附件的电子邮件?

使用Google Apps脚本响应Google Calendar API的推送通知

使用FCM Firebase节点JS Express发送批量推送通知

使用Gmail API Node.js创建Gmail过滤器,错误:过滤器没有任何条件

使用SignalR推送通知

Gmail API推送通知重复的邮件ID

如何在Node.JS中使用gmail API创建带有附件的草稿消息?

收到来自gmail users.watch API的推送通知后,如何读取用户gmail?

如何使用Gmail API在Node.js服务器中连接我的G-Suite

使用Gmail API Node.js客户端发送大型附件(> 5 MB)

使用Api使用推送通知

使用Node.js推送通知

Node.js GCM推送通知允许的ID数量?

CRON Node.js Gmail API脚本

使用node.js gmail api列出收件箱消息

标头未设置 node.js api 推送通知

如何设置 Gmail 推送通知

使用 mongoose 和 fcm 与 node.js 推送通知

如何在节点js中使用Gmail api回复threadId?

无法使用 REST API 发送 FCM 推送通知