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

时间:2016-11-07 16:11:27

标签: javascript node.js gmail-api

看起来很简单,我似乎无法弄清楚如何使用Google的Gmail API设置草稿的收件人。 documentation表示users.messages Resource对象包含payload对象,该对象包含headers对象,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)
  ]
},

在这些标题中,我认为你设置了" To"草案的一部分,因为文件说

  

此邮件部分的标题列表。对于代表整个消息有效负载的顶级消息部分,它将包含标准的RFC 2822电子邮件标头,例如To,From和Subject。

然而,当我提出类似于此的请求时

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

草稿的To部分仍然是空的。任何解决方案或建议?

2 个答案:

答案 0 :(得分:1)

在您的请求中,您有:

"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)
  ]
},

答案 1 :(得分:1)

因此,我似乎误解了Gmail API上的文档。当您向drafts.c​​reate发送请求时,您需要提供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);
    }
  )
}