Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
mail.ts 2.07 KiB
import nodemailer from "nodemailer";
import path from 'path';
import fs from 'fs';
import Handlebars from 'handlebars';

let transporter: nodemailer.Transporter = undefined;
let ready = false;


let create = async () => {
    transporter = nodemailer.createTransport({
        host: process.env.EMAIL_SERVER,
        port: process.env.EMAIL_Port ? Number(process.env.EMAIL_Port) : (Boolean(process.env.EMAIL_IS_TLS) ? 465 : 587),
        secure: Boolean(process.env.EMAIL_IS_TLS),
        auth: {
            user: process.env.EMAIL_USERNAME,
            pass: process.env.EMAIL_PASSWORD
        }
    });
    transporter.verify(function (error, success) {
        if (error) {
            console.error("Error verifying Email connection: " + error);
            process.exit(9)
        } else {
            ready = true;
        }
    });
}
create();

// Construct Templates and load to RAM
let templating: { [templateName: string]: { html: HandlebarsTemplateDelegate, txt: HandlebarsTemplateDelegate } } = {};
fs.readdirSync('./assets').forEach(file => {
    if (file.includes('.html')) {
        try {
            templating[file.split('.')[0]] = {
                html: Handlebars.compile(fs.readFileSync(path.join("./assets", file), 'utf8')),
                txt: Handlebars.compile(fs.readFileSync(path.join("./assets", file.split('.')[0] + '.txt'), 'utf8'))
            };
        } catch (e) {
            console.error(`Couldn't load template '${file}'`, e)
        }
    }
});

const sendMail = (template: "notification", to: string, subject: string, replace: { [toReplace: string]: string }) => {
    if (!ready || !templating[template]) {
        console.error(ready, templating[template])
        return
    }
    transporter.sendMail({
        from: `"${process.env.Application_Name}" <${process.env.EMAIL_FROM_ADDR}>`,
        to: to,
        subject: subject,
        text: templating[template].txt(replace),
        html: templating[template].html(replace)
    }, (err, info) => {
        if (err) return console.log('error', JSON.stringify(err));
        return null;
    });
}

export default sendMail