我正在使用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
console.log
实时更改邮箱中的更改,而无需重新启动nodejs应用程序。谢谢。请帮助=)。
编辑:我对webhooks没有事先的了解,所以如果有人能确切解释我接下来要做什么,那将非常好。
事实证明,下一步是使用Google Cloud Pub / Sub API:使用Pull接收消息。
确保适当的授权和用户访问权限。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句