javascript - 我在使用 Gmail API 阅读来自 Gmail 的电子邮件时遇到问题
问题描述
我列出了收件箱中的所有消息,能够查看每封电子邮件的 ID,但我无法通过参数发送它们以使用以下功能搜索每封电子邮件:gmail.users.messages.get
只需返回一条消息:未定义
谁能告诉我为什么会这样?
const fs = require('fs');
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);
});
}
/**
* 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.
*/
function listLabels(auth) {
const gmail = google.gmail({version: 'v1', auth});
gmail.users.labels.list({
userId: 'me',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const labels = res.data.labels;
if (labels.length) {
console.log('Labels:');
labels.forEach((label) => {
console.log(`- ${label.name}`);
});
listMessages(auth);
} else {
console.log('No labels found.');
}
});
}
/************************** My code is below *******************************/
function listMessages(auth){
var gmail = google.gmail('v1');
gmail.users.messages.list({
auth: auth,
userId: 'me',
q : 'has:attachment',
labelIds: 'INBOX',
}, (err, res) => {
if(err){
console.log('Erro ao listar os emails');
}
var message = res;
Object.keys(message).forEach(index => {
console.log(res[index]);
gmail.users.messages.get({
userId: 'me',
id: message[index].id,
format: 'full',
}, (err, res) => {
console.log(res);
})
})
})
}
解决方案
- 您想
gmail.users.messages.get
使用从 检索到的值来检索消息gmail.users.messages.list
。 - 您想使用 googleapis 和 Node.js 来实现这一点。
- 您已经能够使用 Gmail API 从 Gmail 获取值。
修改点:
gmail.users.messages.list
可以使用 检索来自的值res.data
。在您的脚本中,如何修改 fromvar message = res
被修改为var messages = res.data.messages
?- 当您使用
auth: auth
with 时gmail.users.messages.list
,请同时使用 atgmail.users.messages.get
。
我认为这些点可能是您的问题的原因。当以上几点反映到您的脚本时,它变成如下。
修改后的脚本:
从:var message = res;
Object.keys(message).forEach(index => {
console.log(res[index]);
gmail.users.messages.get({
userId: 'me',
id: message[index].id,
format: 'full',
}, (err, res) => {
console.log(res);
})
})
至:
var messages = res.data.messages;
messages.forEach((message) => {
gmail.users.messages.get(
{
auth: auth,
userId: "me",
id: message.id,
format: "full",
},
(err, res) => {
if (err) {
console.log(err);
return;
}
console.log(res.data);
}
);
});
参考:
推荐阅读
- c# - C#应用程序如何删除“再次显示网页,网络浏览器需要重新发送您之前提交的信息......”消息
- python - 如何正确地将 orange3-made 模型应用于我的 Jupiter 笔记本程序
- unity3d - 使用 Unity 将视频传输到 YouTube Streaming API V3
- java - 使用带有 Quarkus 的 Spring DI,本机映像不会暴露 Spring Rest 点
- graphql - 使用 JSON 导入数据时 createSchemaCustomization 中 @link 的行为不一致
- linux - Logrotate 忽略了我的配置文件
- r - 从数据帧转换为时间序列 (ts) 后,无法理解 strptime 的结果格式
- python - INFO:tensorflow:Saver 未创建,因为图中没有要恢复的变量
- django - 如何在 django 127.0.0.1:8000/?uid=Mjg&token=5dj-ddf5e0d6cf0d6f03dfc1 中指定此网址
- arrays - 将数组映射到数组内的对象内 React JS