All files / config mailer.setup.ts

100% Statements 21/21
100% Branches 3/3
100% Functions 1/1
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 507x 7x 7x 7x   7x     7x 7x 7x 7x                         7x 7x 3x 1x   2x 2x 2x           7x                 7x   7x  
import nodemailer from "nodemailer";
import dotenv from "dotenv";
import path from "path";
import hbs from "nodemailer-express-handlebars";
 
dotenv.config();
 
// ---------------NodeMailer Setup---------------------------
let isMailConfigured = false;
const NODEMAILER_FROM = process.env.NODEMAILER_FROM;
const isServiceBasedConfig = !!process.env.NODEMAILER_SERVICE;
const transportOption = {
  auth: {
    user: process.env.NODEMAILER_USER,
    pass: process.env.NODEMAILER_PASS,
  },
  ...(isServiceBasedConfig
    ? { service: process.env.NODEMAILER_SERVICE }
    : {
        host: process.env.NODEMAILER_HOST,
        port: Number(process.env.NODEMAILER_PORT),
        secure: true,
      }),
};
let transporter = nodemailer.createTransport(transportOption);
transporter.verify(function (error: any) {
  if (error) {
    return console.error(`Mailer not connected, Reason: ${error.message}`);
  }
  console.log("Mailer connected");
  console.log(`All mails will be send from ${NODEMAILER_FROM}`);
  isMailConfigured = true;
});
 
// ------------------Setup mail templates--------------------
 
// point to the template folder
const handlebarOptions = {
  viewEngine: {
    partialsDir: path.resolve("./views/templates/mail"),
    defaultLayout: "",
  },
  viewPath: path.resolve("./views/templates/mail"),
};
 
// use a template file with nodemailer
transporter.use("compile", hbs(handlebarOptions));
 
export { transporter, isMailConfigured, NODEMAILER_FROM };