node.js - send email via google http rest api -


i trying send email nodejs running on linux server google gmail resr http api. not using libraries, sending https. have figured out oauth part, have access token , responses google. cannot past various error messages. have posted code below. not obvious emailsend() called after access token google, yeah being 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:

  1. https://tools.ietf.org/html/rfc2822#appendix-a

  2. https://developers.google.com/identity/protocols/oauth2serviceaccount

  3. https://nodejs.org/api/https.html#https_https_request_options_callback

  4. send email using google api access token

tried myself, , 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(); 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -