如何使用Gmail的Node.js API设置收件人

How to set recipients with Gmail's Node.js API

本文关键字:API 设置 收件人 js Node 何使用 Gmail      更新时间:2023-09-26

尽管看起来很简单,但我似乎无法弄清楚如何使用Google的Gmail API设置草稿的收件人。文档指出,users.messages Resource对象包含一个包含headers对象的payload对象,并且该对象headers包含名称-值对。

// example from google's gmail API documentation
"payload": {
  "partId": string,
  "mimeType": string,
  "filename": string,
  "headers": [
    {
      "name": string,
      "value": string
    }
  ],
  "body": users.messages.attachments Resource,
  "parts": [
    (MessagePart)
  ]
},

在这些标题中,我假设您设置了草稿的"收件人"部分,因为文档说

此消息部件上的标头列表。对于表示整个邮件有效负载的顶级邮件部分,它将包含标准 RFC 2822 电子邮件标头,例如"收件人"、"发件人"和"主题"。

但是,当我提出如下所示的请求时

"payload" : {
  "headers" : [
    {
      "name"  : "To",
      "value" : "me"
      // "me" should direct the draft to myself
    }
  ]
}

草稿的"收件人"部分仍留空。有什么解决方案或建议吗?

在您的请求中,您有以下内容:

"headers" : [ "name" : "To", "value" : "me" ]

"headers" 应该是对象的数组,但您的数组不包含任何对象。

相反,它应该看起来像这样:

"headers": [ { "name": "To", "value": "me" } ]

就像他们的例子一样:

"payload": {
  "partId": string,
  "mimeType": string,
  "filename": string,
  "headers": [
    {
      "name": "To",
      "value": "me"
    }
  ],
  "body": users.messages.attachments Resource,
  "parts": [
    (MessagePart)
  ]
},

因此,我似乎误解了有关Gmail API的文档。当您向drafts.create发送请求时,您确实需要提供是users.messages Resource,但是,并非所有请求都是可写的。只有threadIdlabelIdsraw是可写对象。事实证明,您根本不应该使用有效载荷来设置ToFrom等。您应该将它们包含在原始数据中。

我的新代码看起来像这样

let create = (toAddress, subject, content, callback) => {
  gmail.users.drafts.create(
    {
      'userId'  : 'me',
      'resource' : {
        'message' : {
          'raw' : base64.encodeURI(
                    `To:${toAddress}'r'n` + // Who were are sending to
                    `Subject:${subject}'r'n` + // Subject
                    `Date:'r'n` + // Removing timestamp
                    `Message-Id:'r'n` + // Removing message id
                    `From:'r'n` + // Removing from
                    `${content}` // Adding our actual message
                  )
        }
      }
    },
    (err, response) => {
      // Do stuff with response
      callback(err, response);
    }
  )
}