首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用gmail api检查给定标头的所有传入消息

如何使用gmail api检查给定标头的所有传入消息
EN

Stack Overflow用户
提问于 2020-12-10 09:08:29
回答 1查看 55关注 0票数 1

这是我为gmail api编写的代码。我的逻辑是希望为list函数的回调中的每条消息运行get消息。所以我的控制台应该记录每条消息id的信息,但是当我运行这段代码时,什么也没有记录。我知道list函数正在工作,并且在循环运行之前,日志会显示数组中每条消息的in。然而,我不确定为什么循环不能工作。

代码语言:javascript
运行
复制
const fs = require('fs')
const readline = require('readline')
const { google } = require('googleapis')

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), listMessages)
})

/**
 * 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}`)
        })
      } else {
        console.log('No labels found.')
      }
    },
  )
}
function listMessages(auth) {
  const gmail = google.gmail({ version: 'v1', auth })
  const arr = []
  gmail.users.messages.list(
    {
      userId: 'me',
    },
    (err, res) => {
      if (err) return console.log('The API returned an error: ' + err)
      const labels = res.data
      const lab = labels.messages
      lab.map((x) => arr.push(x.id))
    },
  )
  for (let i = 0; i < arr.length; i++) {
    gmail.users.messages.get(
      {
        id: i,
        userId: 'me',
      },
      (err, res) => {
        if (err) return console.log('The API returned an error: ' + err)
        const label = res.data
        console.log(i)
        console.log(label)
      },
    )
  }
}
EN

回答 1

Stack Overflow用户

发布于 2020-12-10 16:51:55

有一个小的逻辑错误

不应该是id: i,而应该是id: arr[i]

代码语言:javascript
运行
复制
 for (let i = 0; i < arr.length; i++) {
    gmail.users.messages.get(
      {
        id: arr[i],
        userId: 'me',
      },
...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65227126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档