Send email via google http rest api

I am trying to send an email from a NodeJS running on a Linux server to the Google Gmail HTTP API. Don't use libraries, just submit https

. I figured out the OAuth part, have an access token, and get responses from google. But I can't get past the error messages. I posted the code below. It's not obvious, but it EmailSend()

gets called after I get the access token from google, so yes, it gets called.

var emailStr = new Buffer(
      "Content-Type: text/plain; charset=\"UTF-8\"\n" +
      "MIME-Version: 1.0\n" +
      "Content-Transfer-Encoding: 7bit\n" +
      "to: SOMEONE@gmail.com\n" +
      "from: SOMEONEELSE@MYDOMAIN.com\n" +
      "subject: Subject Text\n\n" +

      "The actual message text goes here"
).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
//var emailBase64UrlSafe = Rtrim( emailStr, '=' );
//var emailBase64UrlSafe = JsStrToUrlSafe ( emailStr );
var emailBase64UrlSafe = emailStr;

var http = require('https');
function EmailSend() {

  var post_data = emailBase64UrlSafe;
  var post_options = {
      hostname: 'www.googleapis.com',
      port: '443',
      path: '/gmail/v1/users/me/messages/send',
      method: 'POST',
      headers: {
        "Authorization": 'Bearer '+googleAccessKey['access_token'],
        "Content-Type" : "application/json; charset=UTF-8"
      },
  };
  console.log( post_options );

  var post_req = http.request(post_options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
          console.log('Response: ' + chunk);
      });
  });
  post_req.write(JSON.stringify({ "raw": emailBase64UrlSafe }));
  post_req.end();
}; /* end EmailSend() */

      

Response: {
"error": {
 "errors": [
  {
   "domain": "global",
   "reason": "failedPrecondition",
   "message": "Bad Request"
  }
 ],
 "code": 400,
 "message": "Bad Request"
}

      

Resources used:

+3


source to share


1 answer


Tried this for myself and it worked!



var http = require('https');

var mail = new Buffer(
    "From: example@gmail.com\n" +
    "To: example@gmail.com\n" +
    "Subject: Subject Text\n\n" +

    "Message text"
).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');


var post_options = {
  hostname: 'www.googleapis.com',
  port: '443',
  path: '/gmail/v1/users/me/messages/send',
  method: 'POST',
  headers: {
    "Authorization": 'Bearer <ACCESS_TOKEN>',
    "Content-Type" : "application/json"
  }
};

var post_req = http.request(post_options, function(res) {
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
      console.log('Response: ' + chunk);
  });
});

post_req.write(JSON.stringify({ "raw": mail }));
post_req.end();

      

+1


source







All Articles