Skip to content

Instantly share code, notes, and snippets.

@voidnerd
Last active July 17, 2020 03:57
Show Gist options
  • Save voidnerd/c1f1468f4389d6a8dd18b479fa4c7f7e to your computer and use it in GitHub Desktop.
Save voidnerd/c1f1468f4389d6a8dd18b479fa4c7f7e to your computer and use it in GitHub Desktop.
Email Templating Nodejs Helper
const nodemailer = require("nodemailer");
const path = require("path");
const hbs = require("nodemailer-express-handlebars");
const exphbs = require("express-handlebars");
const Handlebars = require("handlebars");
const {
allowInsecurePrototypeAccess,
} = require("@handlebars/allow-prototype-access");
/** Start Mail Helper */
class Mail {
constructor() {
this.mailer;
this.SUBJECT = "";
this.FROM = process.env.MAIL_FROM;
this.DATA = {};
this.TO = "";
this.viewEngine;
this.options;
}
subject(subject) {
this.SUBJECT = subject;
return this;
}
from(from) {
this.FROM = from;
return this;
}
to(to) {
this.TO = to;
return this;
}
template(template) {
this.TEMPLATE = template;
return this;
}
data(data) {
this.DATA = data;
return this;
}
send() {
this.mailer = nodemailer.createTransport({
host: process.env.MAIL_HOST,
port: process.env.MAIL_PORT,
secure:
process.env.MAIL_ENCRYPTION === "ssl" ||
process.env.MAIL_ENCRYPTION === "tls",
auth: {
user: process.env.MAIL_USERNAME,
pass: process.env.MAIL_PASSWORD,
},
});
this.viewEngine = exphbs.create({
defaultLayout: false,
extname: "hbs",
handlebars: allowInsecurePrototypeAccess(Handlebars),
});
this.options = {
viewEngine: this.viewEngine,
viewPath: path.join(__dirname, `./views/mails/`),
extName: ".hbs",
};
this.mailer.use("compile", hbs(this.options));
const mail = {
from: `"${process.env.APP_NAME}" <${this.FROM}>`,
to: this.TO,
subject: this.SUBJECT,
template: this.TEMPLATE,
context: this.DATA,
};
return this.mailer.sendMail(mail);
}
}
/** End Mail Helper */
module.exports = { Mail };
/** Usage */
let mail = new Mail();
mail.to(user.email)
.template("verify")
.subject("Verify Your Email Address")
.data(mailData)
.send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment