Send email using Google API with only access token - node.js

I want to send an email through Google API without the unnecessary OAUTH2 parameters. I only have the access_token and the refresh_token of that user.
How can I send an email through Gmail API through a basic POST request in NodeJS, with Request npm plugin?

abraham is correct, but I just thought I'd give you an example.
var request = require('request');
server.listen(3000, function () {
console.log('%s listening at %s', server.name, server.url);
// Base64-encode the mail and make it URL-safe
// (replace all "+" with "-" and all "/" with "_")
var encodedMail = new Buffer(
"Content-Type: text/plain; charset=\"UTF-8\"\n" +
"MIME-Version: 1.0\n" +
"Content-Transfer-Encoding: 7bit\n" +
"to: reciever#gmail.com\n" +
"from: sender#gmail.com\n" +
"subject: Subject Text\n\n" +
"The actual message text goes here"
).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
request({
method: "POST",
uri: "https://www.googleapis.com/gmail/v1/users/me/messages/send",
headers: {
"Authorization": "Bearer 'access_token'",
"Content-Type": "application/json"
},
body: JSON.stringify({
"raw": encodedMail
})
},
function(err, response, body) {
if(err){
console.log(err); // Failure
} else {
console.log(body); // Success!
}
});
});
Don't forget to change the reciever and sender email address for the example to work.

There are two methods for attaching OAuth2 access_tokens to a Google API request.
Using the access_token query parameter like this: ?access_token=oauth2-token
Using the HTTP Authorization header like this: Authorization: Bearer oauth2-token
The second one is prefered for POST requests so the raw HTTP request for sending an email would look something like this.
POST /gmail/v1/users/me/messages/send HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer oauth2Token
{"raw":"encodedMessage"}

Related

Authorisation in Drchrono

For authorization at DRchrono, I had created a GET request at https://drchrono.com/o/authorize/ with a redirect URL and clientId, as soon as I click on authorize I redirect to my redirect URL with code value in params,
then I made a POST request on https://drchrono.com/o/token/ via postman with this
{
"code":"x4xzqXXjlBWeeQxEzjyE8thFTIW0eT",
"grant_type": "authorization_code",
"redirect_uri": "",
"client_id": " ",
"client_secret": ""
}
client_id and client_secret value taken from DrChrono API management page.
After making a post instead of getting the access token, I get "400 bad requests" in response.
I am not getting what that thing I am missing.
for doing all this thing I followed DRchrono official document :
https://drchrono.com/api-docs/v4?application=4217#section/Authorization/Initial-authorization
Can anyone help me with this??
My issue got resolved by making these 2 changes:
while making the post request we have to pass
Content-Type=application/x-www-form-urlencoded
in header
const Header = {
"Content-Type": "application/x-www-form-urlencoded",
};
we also need to convert our json object into x-www-form-urlencoded, like this:
var postData = {
code:query.code,
grant_type: "authorization_code",
redirect_uri: " ",
client_id: " ",
client_secret: " ",
};
var encodedData = "";
for (key in postData) {
encodedData += encodeURIComponent(key)+"="+encodeURIComponent(postData[key])+"&";
}
and then finally pass Header, encodedData value in post request
request.post("https://drchrono.com/o/token/", (data = encodedData), {
headers: Header,
}) .then((res) => {
console.log("RESPONSE RECEIVED: ", res.data);
})
This article helped me for testing the Authentication from postman: http://drchronoapi.wpengine.com/connecting-to-drchronos-api-via-postman/
Hope this helps to others who faced similar issue :)

Unable to send mail using gmail api node js

I have followed gmail api for sending email. I am getting error as:
"message": "400 - \"{\n \\"error\\": {\n \\"errors\\": [\n {\n \\"domain\\": \\"global\\",\n \\"reason\\": \\"invalidArgument\\",\n \\"message\\": \\"'raw' RFC822 payload message string or uploading message via /upload/* URL required\\"\n }\n ],\n \\"code\\": 400,\n \\"message\\": \\"'raw' RFC822 payload message string or uploading message via /upload/* URL required\\"\n }\n}\n\""
Here is the piece of code I have written for sending mail using gmail api with node.js. Help me out to resolve the issue.
router.post('/composeMail', async (req, res, next) => {
function makeBody(to, from, subject, message) {
let str = ["Content-Type: text/plain; charset=\"UTF-8\"\n",
"Content-length: 5000\n",
"Content-Transfer-Encoding: message/rfc822\n",
"to: ", to,"\n",
"from: ", from,"\n",
"subject: ", subject,"\n\n",
message
].join('');
console.log("String: ", str);
// let encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
let encodedMail = btoa(str).replace(/\+/g, '-').replace(/\//g, '_');
return encodedMail;
}
let raw = makeBody("dinesh.kumar#gmail.com", "dinesh.kumar#gmail.com", "Test mail", "Everything is fine");
let obj = {};
obj.raw = raw;
let body = JSON.stringify(obj);
let option = {
url: "https://www.googleapis.com/gmail/v1/users/userId/messages/send",
method: 'POST',
headers: {
'Authorization': `Bearer ${req.query.access_token}`
},
qs: {
userId: 'me'
},
body: body
};
await request(option).then(body => {
return res.apiOk(body);
}).catch(err => {
return res.apiError(err);
})
});
You want to send an email using Gmail API by the request module.
If my understanding is correct, how about this modification? I think that there are several answers. So please think of this as one of them.
Modification points:
Please use https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send as the endpoint.
Use the value as a string.
Add 'Content-Type': 'message/rfc822' to the headers.
Modified script:
Please modify makeBody() as follows.
function makeBody(to, from, subject, message) {
let str = [
"to: ", to, "\n",
"from: ", from, "\n",
"subject: ", subject, "\n\n",
message,
].join('');
return str;
}
Please modify option as follows.
let raw = makeBody("dinesh.kumar#gmail.com", "dinesh.kumar#gmail.com", "Test mail", "Everything is fine");
const userId = 'me'; // Please modify this for your situation.
let option = {
url: "https://www.googleapis.com/upload/gmail/v1/users/" + userId + "/messages/send",
method: 'POST',
headers: {
'Authorization': `Bearer ${req.query.access_token}`,
'Content-Type': 'message/rfc822',
},
body: raw,
};
Note:
This modified script supposes that Gmail API is enabled at API console and the required scope for sending emails is included in the scopes of access token.
Reference:
Users.messages: send
In my environment, I could confirm that this modified script worked fine. But if this was not what you want, I'm sorry.

Receiving 401 "Bad Credentials" when hitting github API endpoint

I'm trying to build a CLI that uses the GitHub api. I instantly run into a road block. Although I've read the introductory docs up and down, I don't see what is wrong in the following code.
var userData = require('../userData');
var request = require('request');
module.exports = {
hitEndpoint: function() {
var username = "<redacted_user_name>",
password = "<redacted_password>",
auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var options = {
method: 'get',
url: " https://api.github.com/<redacted_user_name>",
headers: {
"Authorization": auth,
"User-Agent": "<redacted_whatever_doesnt_matter>"
}
}
request(options, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
},
}
prints:
error: null
statusCode: 404
body: {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
To get your own profile you'll want to hit the authenticated user endpoint, you shouldn't replace this with your own username, GitHub will know who you are based on your authentication string:
https://api.github.com/user
To get another user's profile you'll want to hit the users endpoint:
https://api.github.com/users/:username

Execute OAuth2 with the Mailchimp API in NodeJS

I've been following MailChimp's OAuth2 tutorial (https://developer.mailchimp.com/documentation/mailchimp/guides/how-to-use-oauth2/) but got stuck when making a post request with the code and secret/key params. The closest I've gotten is a 400 Bad Request response. My code:
var args = {
headers: { "Content-Type": "application/json" },
body: "grant_type=authorization_code&client_id=" + client_id + "&client_secret=" + client_secret + "&redirect_uri=" + encoded_url + "&code=" + req.query.code,
url: "https://login.mailchimp.com/oauth2/token"
};
var r = request.post(args, function(err, req, body){
console.log(err)
console.log(req)
})
Okay, I was running in to the same thing, and finally found it. My code was very similar to yours:
this.globals.request({
method: "POST",
uri: "https://login.mailchimp.com/oauth2/token",
form: {
grant_type: "authorization_code",
client_id: this.globals.mailchimp_client_id,
client_secret: this.globals.mailchimp_client_secret,
redirect_uri: encodeURIComponent(fullUrl),
code: req.query.code
}
},
function (error, response, body) {
if (error || response.statusCode !== 200) {
self.globals.logger.debug(self.moduleName, "getMailchimpToken", "Error " + response.statusCode + "(" + response.statusMessage + ") from mailchimp: " + error, true);
body = {};
}
self.globals.logger.debug(self.moduleName, "getMailchimpToken", "got body: " + JSON.stringify(body), false);
deferred.resolve(body);
});
The problem here, and I suspect with yours, is that you are using an encoded URL in the form data, but request will encode it again. When I looked at the querystring, I saw things like
&redirect_uri=http%253A%252F%252F
where the %s were being re-encoded. Changed encodeURIComponent(fullUrl), to just fullUrl, and it worked.
One important note that was not clear to me - the redirect_uri should be the same one used in the OAuth call, including the path. Note that per the Mailchimp docs, you can vary the path in the actual call from the redirect_url used when registering the app, which is where this can be important.

Spotify WebAPI authorization - client credentials flow error invalid_client

Straight forward question, hopefully with a straight forward answer. I'm attempting to implement the client credentials flow via Node.js, using request. Here's my code
var request = require('request');
var payload = config.spotify.clientID + ":" + config.spotify.clientSecret;
var encodedPayload = new Buffer(payload).toString("base64");
var opts = {
url: "https://accounts.spotify.com/api/token",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer " + encodedPayload
},
body: "grant_type=client_credentials&scope=playlist-modify-public playlist-modify-private"
};
request(opts, function (err, res, body) {
console.log('error', err);
console.log('status', res.statusCode);
console.log('body', body);
});
No matter what I do, the response body is always
{"error":"invalid_client"}
I've tried making the request using curl, with the same outcome.
$ curl -X POST -H 'Authorization: Bearer <base64encoded client_id:client_secret>' -d 'grant_type=client_credentials&scope=playlist-modify-public playlist-modify-private' https://accounts.spotify.com/api/token
That would imply that it's a problem with the credentials. I'm definitely using the right clientID and clientSecret for my app, which leads me to believe that it's the encoding that's causing the problem.
Am I doing the encoding right? If so, what else might be the cause?
Replace
"Authorization": "Bearer " + ...
with
"Authorization": "Basic " + ...
and see if it works better.

Resources