Node.js-Google API发送电子邮件未按线程分组

时间:2019-04-06 07:48:27

标签: node.js gmail-api

作为小型电子邮件CRM项目的一部分,我创建了一个 Nodejs 应用。当我通过gmail send api发送电子邮件时,邮件未分组。

const sendObject = {}
output.data.messages.map(each => {
  sendObject.threadId = each.threadId // ThreadID is unique.
  each.payload.headers.map(head => {
    if (head.name === 'From') {
      sendObject.replyTo = head.value
    } else if (head.name === 'Subject') {
      if (head.value.indexOf('Re:') >= 0) {
        sendObject.subject = head.value  
      } else {
        sendObject.subject = 'Re: ' + head.value
      }
    } else if (head.name === 'Message-Id') {
      sendObject.inReplyTo = head.value // The last thread messageId is inserted into In-Reply-To tag
      sendObject.reference.push(head.value) // All the messageId are appended as part of References tag
    }
  })
})


const email_lines = []
email_lines.push('References:' + sendObject.reference.join(' '))
email_lines.push('In-Reply-To:' + sendObject.inReplyTo)
email_lines.push('Subject: ' + sendObject.subject)
email_lines.push('To:' + sendObject.replyTo)

email_lines.push('')
email_lines.push(req.body.body)

const email = email_lines.join('\r\n').trim()

let base64EncodedEmail = new Buffer(email).toString('base64')
base64EncodedEmail = base64EncodedEmail.replace(/\+/g, '-').replace(/\//g, '_')

emailConfig.gmail.users.messages.send({
  userId: 'me',
  threadId: sendObject.threadId,
  resource: {
    raw: base64EncodedEmail
  }
}, async (err) => {
  if (err) {
    console.log('The Threads API returned an error: ' + err)
  }
})

当我通过浏览器登录gmail时,我可以看到2封不同的电子邮件,而不是一个主题。

1 个答案:

答案 0 :(得分:0)

您应将 threadId 放在资源中。

  const response = await this.gmail.users.messages.send({
    auth: this.oAuth2Client,
    userId: this.gmailAddress,
    uploadType: 'multipart',
    resource: {
      threadId: email.threadId,
      raw: raw
    }
  })

有关更多详细信息,您可以检查我的Gmail-API-wrapper here