Skip to content

Instantly share code, notes, and snippets.

@mucahitnezir
Last active July 11, 2018 08:24
Show Gist options
  • Save mucahitnezir/7d1ce66d0dadb7120f40167e3fba2864 to your computer and use it in GitHub Desktop.
Save mucahitnezir/7d1ce66d0dadb7120f40167e3fba2864 to your computer and use it in GitHub Desktop.
Node.js mail sender helper file.
COMPANY_NAME = your-company-name
MAIL_SERVICE = mail-service-name
MAIL_ADDRESS = yourname@yoursite.com
MAIL_PASSWORD = mail-password
'use strict';
const nodemailer = require('nodemailer')
, pug = require('pug')
, Promise = require('bluebird')
, fs = Promise.promisifyAll(require('fs'));
const sendMail = (to, subject, mailContent, callback) => {
// Create transporter
const transporter = nodemailer.createTransport({
service: process.env.MAIL_SERVICE,
auth: {
user: process.env.MAIL_ADDRESS,
pass: process.env.MAIL_PASSWORD
}
});
// Setup email data with unicode symbols
let mailOptions = {
from: process.env.COMPANY_NAME + ' <' + process.env.MAIL_ADDRESS + '>',
to: to,
subject: process.env.COMPANY_NAME + ' | ' + subject,
html: mailContent
};
// Send mail
transporter.sendMail(mailOptions, (error) => {
if (error)
callback(error, null);
else
callback(null, true);
});
};
module.exports = (to, subject, content, callback) => {
if (typeof content === 'object') {
// Define template pug file and params
const template = process.cwd() + '/app/views/mail_templates/' + content.view + '.pug'
, params = content.params;
// Read pug file
fs
.readFileAsync(template, 'utf8')
.then((file) => {
return pug.compile(file, {filename: template})(params);
})
.then((htmlContent) => {
sendMail(to, subject, htmlContent, callback);
}).catch((err) => {
callback(err, null);
});
} else {
sendMail(to, subject, content, callback);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment