Skip to content

Instantly share code, notes, and snippets.

@junicodes
Forked from voidnerd/Mail.js
Created July 5, 2020 09:19
Show Gist options
  • Save junicodes/6495f9e8c9c384afed278a1446384beb to your computer and use it in GitHub Desktop.
Save junicodes/6495f9e8c9c384afed278a1446384beb 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