Reputation: 191
I am trying to send email from NodeJS running on a Linux server to Google Gmail RESR HTTP API. Not using libraries, just sending https
. I have figured out the OAuth part, have an access token and get responses from google. But I cannot get past various error messages. I have posted the code below. It is not obvious but EmailSend()
is called after I get the access token from google, so yeah it is 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: [email protected]\n" +
"from: [email protected]\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:
https://developers.google.com/identity/protocols/OAuth2ServiceAccount
https://nodejs.org/api/https.html#https_https_request_options_callback
Upvotes: 3
Views: 5210
Reputation: 112787
Tried it for myself, and it worked!
var http = require('https');
var mail = new Buffer(
"From: [email protected]\n" +
"To: [email protected]\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();
Upvotes: 4