使用Google GMail游乐场时,为什么我会一直收到“400无效标题”回复?

时间:2016-12-16 15:32:29

标签: gmail gmail-api

我花了两天时间试图通过Google OAuth playground发送电子邮件,但没有运气。这是我要发送的原始邮件:

To: "Stanley Smith" <stan.smith@yahoo.com>\r\nContent-type: text/html;charset=iso-8859-1\r\nMIME-Version: 1.0\r\nSubject: this would be the subject\r\n\r\nThis is the email sent by Stanley Smith

我base64编码(url-safe encode),然后将编码的字符串放在请求体中

{
    "raw": "VG86ICJTdGFubGV5IFNtaXRoIiA8c3Rhbi5zbWl0aEB5YWhvby5jb20+XHJcbkNvbnRlbnQtdHlwZTogdGV4dC9odG1sO2NoYXJzZXQ9aXNvLTg4NTktMVxyXG5NSU1FLVZlcnNpb246IDEuMFxyXG5TdWJqZWN0OiB0aGlzIHdvdWxkIGJlIHRoZSBzdWJqZWN0XHJcblxyXG5UaGlzIGlzIHRoZSBlbWFpbCBzZW50IGJ5IFN0YW5sZXkgU21pdGgK"
}

然后我点击发送请求,我不断收到此错误:

HTTP/1.1 400 Bad Request
Content-length: 188
X-xss-protection: 1; mode=block
X-content-type-options: nosniff
Expires: Fri, 16 Dec 2016 15:27:27 GMT
Vary: Origin,X-Origin
Server: GSE
Cache-control: private, max-age=0
Date: Fri, 16 Dec 2016 15:27:27 GMT
X-frame-options: SAMEORIGIN
Content-type: application/json; charset=UTF-8
{
  "error": {
    "code": 400, 
    "message": "Invalid to header", 
    "errors": [
      {
        "domain": "global", 
        "message": "Invalid to header", 
        "reason": "invalidArgument"
      }
    ]
  }
}

我正在关注RFC 2822,所以我不知道为什么会收到此错误。为什么我会收到此错误?

2 个答案:

答案 0 :(得分:3)

我不完全确定你为什么会遇到这个错误。如果您重新排列标题并将其编码为base64 url​​-safe:

,则可以使用它
btoa(
  "From: \"Stanley Toles\" <stan.toles@yahoo.com>\r\n" +
  "To: \"Stanley Toles\" <stan.toles@yahoo.com>\r\n" +
  "Subject: this would be the subject\r\n" +
  "Content-type: text/html;charset=iso-8859-1\r\n\r\n" +

  "This is the email sent by Stanley Toles"
).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');

答案 1 :(得分:1)

这篇文章对我有很大帮助。感谢您提出问题Rob。

最初,我在电子邮件中使用以下代码:

let email = {message: "To: firstname lastname<someperson@gmail.com>  From: firstname 
lastname <someperson@gmail.com> Subject: Saying Hello  Date: Tue, 9 Nov 2018 17:20:06 
-0600 
Message-ID: <1234@local.machine.example>  This is a message just to say hello."}

阅读您的帖子后,我意识到我错过了回车符。这是我的最终答案,该答案使用javascript中的google gmail api发送电子邮件:

function sendMessage(auth) {

    let email = {message: `To: "first last" <someperson@gmail.com>\r\nContent-type: 
    text/html;charset=iso-8859-1\r\nMIME-Version: 1.0\r\nSubject: this would be the 
    subject\r\n\r\nThis is the email sent by Stanley Toles`}

    let base64EncodedEmail = Base64.encodeURI(email.message);

    gmail.users.messages.send({'auth': auth, 'userId': 'me',  'resource': {
     "payload": {
      "headers": [
       {name: "To", value: "first last <somepersonsemail@gmail.com>"},
       {name: 'From', value: 'first last <somepersonsemail@gmail.com>'},
       {name: 'Subject', value: 'Saying Hello'}]
    },
    'raw': base64EncodedEmail,


    }},function(err,response){

    if(err) throw err;

    console.log(response);
   });
  }