Skip to content

Instantly share code, notes, and snippets.

@MatteoPierro
Created September 30, 2018 13:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MatteoPierro/f8d4c0883fa5037ef5e14f8c10133234 to your computer and use it in GitHub Desktop.
Save MatteoPierro/f8d4c0883fa5037ef5e14f8c10133234 to your computer and use it in GitHub Desktop.
Send mail with GMail Api
const mailService = require('./mailService')
mailService.send({
to: 'an@email.com',
subject: 'Greetings',
text: 'Hello dude!'
});
const fs = require('fs');
const readline = require('readline');
const { google } = require('googleapis');
const Base64 = require('js-base64').Base64;
const MailComposer = require('nodemailer/lib/mail-composer');
const SCOPES = ['https://www.googleapis.com/auth/gmail.send'];
const TOKEN_PATH = 'token.json';
function sendEmail(email) {
fs.readFile('gmail.credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
authorize(JSON.parse(content), send(email));
});
}
function authorize(credentials, callback) {
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
function getNewToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
function send(email) {
return (auth) => {
const gmail = google.gmail({ version: 'v1', auth });
const mail = new MailComposer(email);
mail.compile().build((err, message) => {
if (err) return console.log('MailComposer returned an error: ' + err);
console.log(`message ${message.toString('utf8')}`)
gmail.users.messages.send({
userId: 'me',
resource: {
raw: Base64.encodeURI(message.toString('utf8'))
}
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
console.log(`Server response ${res.status} ${res.statusText}`);
});
});
}
}
module.exports = {
send: sendEmail
}
{
"name": "send-email",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"googleapis": "^34.0.0",
"js-base64": "^2.4.9",
"nodemailer": "^4.6.8"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment