Skip to content

Instantly share code, notes, and snippets.

@thiagorossener
Created January 3, 2018 14:50
Show Gist options
  • Save thiagorossener/dc8f1d97ad80ab863245ef8b0ce2aecc to your computer and use it in GitHub Desktop.
Save thiagorossener/dc8f1d97ad80ab863245ef8b0ce2aecc to your computer and use it in GitHub Desktop.
'use strict';
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
// If modifying these scopes, delete your previously saved credentials
// which location is specified at config/config.json in the property
// generatedTokenPath
var SCOPES = ['https://www.googleapis.com/auth/gmail.send'];
var config = JSON.parse(fs.readFileSync(__dirname + '/../../config/config.json', 'utf8'))[process.env.NODE_ENV || 'dev'];
var CLIENT_SECRET_PATH = config.gmailApi.clientSecretPath;
var GENERATED_TOKEN_PATH = config.gmailApi.generatedTokenPath;
module.exports = (function () {
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
var authorize = function(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(GENERATED_TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
};
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
var getNewToken = function(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
};
/**
* Store token to disk be used in later program executions.
*
* @param {Object} token The token to store to disk.
*/
var storeToken = function(token) {
fs.writeFile(GENERATED_TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + GENERATED_TOKEN_PATH);
};
/**
* Structure the email, and send it
*
* @param {auth} the authentication gotten from the credentials.
* @param {from} the email from where the email will be sent.
* @param {to} the email address that is going to receive the email.
* @param {subject} the email's subject.
* @param {content} the email's content.
*/
function sendEmail(auth, from, to, subject, content, onSuccess, onFail) {
var contentType = 'text/html; charset=UTF-8';
//Treating the subject so UTF-8 characters are handled correctly
subject = '=?UTF-8?B?' + new Buffer(subject).toString('base64').replace(/\+/g, '-').replace(/\//g, '_') + '?=';
// The Gmail API requires url safe Base64
// (replace '+' with '-', and '/' with '_')
var encodedEmail = new Buffer(
'From: ' + from + '\r\n' +
'To: ' + to + '\r\n' +
'Subject: ' + subject + '\r\n' +
'Content-Type: ' + contentType + '\r\n\r\n' +
content
).toString('base64').replace(/\+/g, '-').replace(/\//g, '_');
var gmail = google.gmail('v1');
var request = gmail.users.messages.send({
auth: auth,
userId: 'me',
resource: {
raw: encodedEmail,
html: true
}
}, function (err, result) {
if(err)
{
onFail(err);
}else{
onSuccess();
}
});
};
/**
* Load the credentials from client_secret.json and send them to be authorized
*
* @param {from} the email from where the email will be sent.
* @param {to} the email address that is going to receive the email.
* @param {subject} the email's subject.
* @param {messageContent} the email's content.
*/
var authorizeAndSendEmail = function(from, to, subject, messageContent, onSuccess, onFail) {
// Load client secrets from a local file.
fs.readFile(CLIENT_SECRET_PATH, function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials,
// then call the Gmail API.
authorize(JSON.parse(content), function(auth){
sendEmail(auth, from, to, subject, messageContent, onSuccess, onFail);
});
});
};
return {
authorizeAndSendEmail: authorizeAndSendEmail
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment