首页 > 解决方案 > Gmail Rest API json 发送消息

问题描述

我无法向 gmail api 发送 json 请求。我可以访问独家新闻https://www.googleapis.com/auth/gmail.send,它允许我访问发送方法。

在谷歌文档中,他们声明其余部分需要以下数据。 https://developers.google.com/gmail/api/reference/rest/v1/users.messages

但我不会填满它们,要放什么?有没有人通过只发送一个json来使用api?

我在堆栈上进行了研究,但没有找到遇到这种困难的人。并且在谷歌文档上没有例子。

{
  "id": string,
  "threadId": string,
  "labelIds": [
    string
  ],
  "snippet": string,
  "historyId": string,
  "internalDate": string,
  "payload": {
    object (MessagePart)
  },
  "sizeEstimate": integer,
  "raw": string
}

标签: jsonapirestgmail

解决方案


消息应编码为 base64。您可以通过将此代码粘贴到节点 REPL 或在线节点编译器中来生成一个,例如 https://replit.com/languages/nodejs

function createMessageJson(){
    const messages = [
        'From: NAME <foo@email.com>',
        'To: Name <foobar@email.com>',
        'Content-Type: text/html; charset=utf-8',
        'MIME-Version: 1.0',
        'Subject: Re: SUBJECT',
        '',
        'BODY_TEXT',
        '',
    ];


    function encodedMessage (){
        return Buffer.from(messages.join('\n'))
            .toString('base64')
            .replace(/\+/g, '-')
            .replace(/\//g, '_')
            .replace(/=+$/, '');
    }


  return JSON.stringify({
            raw: encodedMessage()
    });
}

console.log(createMessageJson())

推荐阅读