-
-
Save mucahitnezir/7d1ce66d0dadb7120f40167e3fba2864 to your computer and use it in GitHub Desktop.
Node.js mail sender helper file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
COMPANY_NAME = your-company-name | |
MAIL_SERVICE = mail-service-name | |
MAIL_ADDRESS = [email protected] | |
MAIL_PASSWORD = mail-password |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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