Skip to content

Instantly share code, notes, and snippets.

@arvsr1988
Created September 21, 2016 12:30
Show Gist options
  • Save arvsr1988/91d321b96e3c2d231d312223e18864df to your computer and use it in GitHub Desktop.
Save arvsr1988/91d321b96e3c2d231d312223e18864df to your computer and use it in GitHub Desktop.
gmail api integration
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var mimelib = require("mimelib");
let btoa = require('btoa');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/gmail.send'];
var key = require('./client_secret.json');
var jwtClient = new google.auth.JWT(key.client_email, null, key.private_key, SCOPES, null);
jwtClient.authorize(function(err, tokens) {
if (err) {
console.log("error ");
console.log(err);
return;
}
console.log("success");
console.log(tokens);
listMajors(tokens);
});
function listMajors(auth) {
function makeBody(to, from, subject, message) {
var str = ["Content-Type: text/plain; charset=\"UTF-8\"\n",
"MIME-Version: 1.0\n",
"Content-Transfer-Encoding: 7bit\n",
"to: ", to, "\n",
"from: ", from, "\n",
"subject: ", subject, "\n\n",
message
].join('');
var encodedMail = mimelib.foldLine(str);
return encodedMail;
}
function sendMessage(auth) {
var gmail = google.gmail('v1');
var raw = makeBody('toemail@gmail.com', 'fromEmail@gmail.com', 'test subject', 'test message');
gmail.users.messages.send({
access_token : auth.access_token,
userId: 'me',
message: {
raw : btoa(raw)
}
}, function(err, response) {
if(err){
console.log("error");
console.dir(err);
return;
}
console.dir(response);
});
}
sendMessage(auth);
}
//output
/*
{ Error: Bad Request
at Request._callback (/Users/arvinds/code/node_modules/google-auth-library/lib/transporters.js:85:15)
at Request.self.callback (/Users/arvinds/code/node_modules/google-auth-library/node_modules/request/request.js:198:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (/Users/arvinds/code/node_modules/google-auth-library/node_modules/request/request.js:1057:14)
at emitOne (events.js:101:20)
at Request.emit (events.js:188:7)
at IncomingMessage.<anonymous> (/Users/arvinds/code/node_modules/google-auth-library/node_modules/request/request.js:1003:12)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
code: 400,
errors:
[ { domain: 'global',
reason: 'failedPrecondition',
message: 'Bad Request' } ] }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment