Gmail API 使用 Nodejs 推送通知
Gmail API Push Notifications with Nodejs
我正在使用 Nodejs 和 Gmail API 制作一个网络应用程序,它会通知我收到某个标签的电子邮件。
经过一些研究,我找到了这个指南:Push Notifications | Gmail API
但是我停了下来,因为我不知道 this 之后该做什么。
watch()
函数运行良好,并给出了正确的响应。
这是我的完整代码(授权部分取自Gmail API's quickstart guide for 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 制作一个推送通知系统。
- 我不明白 this
之后要做什么
- 我想
console.log
我的邮箱实时变化,不需要重启nodejs应用。
谢谢。请帮助 =).
编辑 :我之前对 webhook 没有任何了解,所以如果有人能准确地解释我下一步该怎么做,那就太好了。
原来下一步是使用 Google 云 Pub/Sub API:Receiving messages using Pull。
确保适当的授权和用户访问权限。
我正在使用 Nodejs 和 Gmail API 制作一个网络应用程序,它会通知我收到某个标签的电子邮件。
经过一些研究,我找到了这个指南:Push Notifications | Gmail API
但是我停了下来,因为我不知道 this 之后该做什么。
watch()
函数运行良好,并给出了正确的响应。
这是我的完整代码(授权部分取自Gmail API's quickstart guide for 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 制作一个推送通知系统。
- 我不明白 this 之后要做什么
- 我想
console.log
我的邮箱实时变化,不需要重启nodejs应用。
谢谢。请帮助 =).
编辑 :我之前对 webhook 没有任何了解,所以如果有人能准确地解释我下一步该怎么做,那就太好了。
原来下一步是使用 Google 云 Pub/Sub API:Receiving messages using Pull。
确保适当的授权和用户访问权限。