Search code examples
gmailgmail-api

Why do I keep getting a "400 invalid to header" response when using the Google GMail playground?


I have spent two days trying to send an email via Google OAuth playground with no luck. Here is the raw message I am trying to send:

To: "Stanley Smith" <[email protected]>\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

I base64 encode (url-safe encode) that and then put the encoded string in the request body as such

{
    "raw": "VG86ICJTdGFubGV5IFNtaXRoIiA8c3Rhbi5zbWl0aEB5YWhvby5jb20+XHJcbkNvbnRlbnQtdHlwZTogdGV4dC9odG1sO2NoYXJzZXQ9aXNvLTg4NTktMVxyXG5NSU1FLVZlcnNpb246IDEuMFxyXG5TdWJqZWN0OiB0aGlzIHdvdWxkIGJlIHRoZSBzdWJqZWN0XHJcblxyXG5UaGlzIGlzIHRoZSBlbWFpbCBzZW50IGJ5IFN0YW5sZXkgU21pdGgK"
}

I then click send request and I keep getting this error:

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

I am following RFC 2822 so I have no idea why I am getting this error. Why am I getting this error?


Solution

  • I'm not entirely sure why you get this error. It works if you rearrange the headers and encode it to base64 url-safe:

    btoa(
      "From: \"Stanley Toles\" <[email protected]>\r\n" +
      "To: \"Stanley Toles\" <[email protected]>\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(/=+$/, '');