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

Posted

技术标签:

【中文标题】如何使用 gmail api 检查给定标头的所有传入消息【英文标题】:How can I check all incoming messages for a given header using the gmail api 【发布时间】:2021-03-21 10:32:30 【问题描述】:

这是我的 gmail api 代码。我的逻辑是我希望为列表函数回调中的每条消息运行获取消息。所以我的控制台应该记录每个消息 id 的信息,但是当我运行这段代码时,什么都没有记录。我知道 list 函数正在工作,并且日志显示循环运行之前数组中每条消息的 id。但是,我不确定为什么循环不起作用。

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

【问题讨论】:

【参考方案1】:

有一点逻辑错误

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

 for (let i = 0; i < arr.length; i++) 
    gmail.users.messages.get(
      
        id: arr[i],
        userId: 'me',
      ,
...

【讨论】:

以上是关于如何使用 gmail api 检查给定标头的所有传入消息的主要内容,如果未能解决你的问题,请参考以下文章

在 gmail api 中搜索特定的 in-reply-to 标头

MIME 标头无法通过 Gmail API

由于 To 标头而被 Gmail API 拒绝的电子邮件

Gmail API 游乐场:发送方法,转换后的 MIME 原始标头在发送时未填充电子邮件字段

如何在 django 中使用 gmail smtp 更改回复和返回路径标头

Gmail NodeJs客户端中的Gmail API userId用例?