Repository: lowercasename/gathio
Pull request #202: Fix ReferenceError: nodemailerTransporter is not defined
Author: login: halkeye
Created: 2025-04-23T22:09:01Z | Merged: 2025-04-29T21:02:13Z

Part of https://github.com/lowercasename/gathio/pull/200 was migrating more code to use the shared init email function, but all the local usages of nodemailerTransporter were missed

I tested this running dev mode. I'll build a new image and try it on my server tonight, but from my testing it should be good.


Diff:
diff --git a/package.json b/package.json
index 15f5f48f..2de0373f 100644
--- a/package.json
+++ b/package.json
@@ -18,6 +18,7 @@
     "author": "",
     "license": "GPL-3.0-or-later",
     "dependencies": {
+        "@sendgrid/helpers": "^8.0.0",
         "@sendgrid/mail": "^6.5.5",
         "@types/cookie-parser": "^1.4.7",
         "activitypub-types": "^1.1.0",
@@ -46,6 +47,7 @@
         "request": "^2.88.2",
         "sanitize-html": "^2.13.0",
         "toml": "^3.0.0",
+        "ts-deepmerge": "^7.0.2",
         "typescript": "^5.4.5",
         "wait-on": "^7.2.0"
     },
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5139a4a7..11f04d96 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -8,6 +8,9 @@ importers:
 
   .:
     dependencies:
+      '@sendgrid/helpers':
+        specifier: ^8.0.0
+        version: 8.0.0
       '@sendgrid/mail':
         specifier: ^6.5.5
         version: 6.5.5
@@ -92,6 +95,9 @@ importers:
       toml:
         specifier: ^3.0.0
         version: 3.0.0
+      ts-deepmerge:
+        specifier: ^7.0.2
+        version: 7.0.2
       typescript:
         specifier: ^5.4.5
         version: 5.4.5
@@ -370,6 +376,10 @@ packages:
     resolution: {integrity: sha512-uRFEanalfss5hDsuzVXZ1wm7i7eEXHh1py80piOXjobiQ+MxmtR19EU+gDSXZ+uMcEehBGhxnb7QDNN0q65qig==}
     engines: {node: '>= 6.0.0'}
 
+  '@sendgrid/helpers@8.0.0':
+    resolution: {integrity: sha512-Ze7WuW2Xzy5GT5WRx+yEv89fsg/pgy3T1E3FS0QEx0/VvRmigMZ5qyVGhJz4SxomegDkzXv/i0aFPpHKN8qdAA==}
+    engines: {node: '>= 12.0.0'}
+
   '@sendgrid/mail@6.5.5':
     resolution: {integrity: sha512-DSu8oTPI0BJFH60jMOG9gM+oeNMoRALFmdAYg2PIXpL+Zbxd7L2GzQZtmf1jLy/8UBImkbB3D74TjiOBiLRK1w==}
     engines: {node: '>=6.0.0'}
@@ -2123,6 +2133,10 @@ packages:
     resolution: {integrity: sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==}
     engines: {node: '>=14'}
 
+  ts-deepmerge@7.0.2:
+    resolution: {integrity: sha512-akcpDTPuez4xzULo5NwuoKwYRtjQJ9eoNfBACiBMaXwNAx7B1PKfe5wqUFJuW5uKzQ68YjDFwPaWHDG1KnFGsA==}
+    engines: {node: '>=14.13.1'}
+
   tslib@1.14.1:
     resolution: {integrity: sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==}
 
@@ -2661,6 +2675,10 @@ snapshots:
       chalk: 2.4.2
       deepmerge: 4.3.1
 
+  '@sendgrid/helpers@8.0.0':
+    dependencies:
+      deepmerge: 4.3.1
+
   '@sendgrid/mail@6.5.5':
     dependencies:
       '@sendgrid/client': 6.5.5
@@ -4563,6 +4581,8 @@ snapshots:
     dependencies:
       punycode: 2.3.1
 
+  ts-deepmerge@7.0.2: {}
+
   tslib@1.14.1: {}
 
   tslib@2.6.2: {}
diff --git a/src/app.ts b/src/app.ts
index 07080818..7ed535cb 100755
--- a/src/app.ts
+++ b/src/app.ts
@@ -1,6 +1,6 @@
 import express from "express";
-import hbs from "express-handlebars";
 import cookieParser from "cookie-parser";
+import { create as createHandlebars, ExpressHandlebars } from "express-handlebars";
 
 import routes from "./routes.js";
 import frontend from "./routes/frontend.js";
@@ -9,29 +9,27 @@ import event from "./routes/event.js";
 import group from "./routes/group.js";
 import staticPages from "./routes/static.js";
 import magicLink from "./routes/magicLink.js";
-
-import { initEmailService } from "./lib/email.js";
 import {
     activityPubContentType,
     alternateActivityPubContentType,
 } from "./lib/activitypub.js";
+import { EmailService } from "./lib/email.js";
+import getConfig from "./lib/config.js";
 
 const app = express();
+const config = getConfig();
 
-app.locals.sendEmails = initEmailService();
-
-// View engine //
-const hbsInstance = hbs.create({
+const hbsInstance = createHandlebars({
     defaultLayout: "main",
     partialsDir: ["views/partials/"],
     layoutsDir: "views/layouts/",
     helpers: {
         plural: function (number: number, text: string) {
-            var singular = number === 1;
+            const singular = number === 1;
             // If no text parameter was given, just return a conditional s.
             if (typeof text !== "string") return singular ? "" : "s";
             // Split with regex into group1/group2 or group1(group3)
-            var match = text.match(/^([^()\/]+)(?:\/(.+))?(?:\((\w+)\))?/);
+            const match = text.match(/^([^()\/]+)(?:\/(.+))?(?:\((\w+)\))?/);
             // If no match, just append a conditional s.
             if (!match) return text + (singular ? "" : "s");
             // We have a good match, so fire away
@@ -41,11 +39,23 @@ const hbsInstance = hbs.create({
                 match[1] + (match[3] || "s")
             ); // Plural case: 'bagel(s)' or 'bagel' --> bagels
         },
-        json: function (context: any) {
+        json: function (context: object) {
             return JSON.stringify(context);
         },
     },
 });
+
+const emailService = new EmailService(config, hbsInstance);
+emailService.verify();
+
+app.use((req: express.Request, _: express.Response, next: express.NextFunction) => {
+    req.hbsInstance = hbsInstance;
+    req.emailService = emailService;
+    next()
+    return
+})
+
+// View engine //
 app.engine("handlebars", hbsInstance.engine);
 app.set("view engine", "handlebars");
 app.set("hbsInstance", hbsInstance);
diff --git a/src/index.d.ts b/src/index.d.ts
index 292e5d34..4811f7f9 100644
--- a/src/index.d.ts
+++ b/src/index.d.ts
@@ -1,14 +1,17 @@
 import "express";
-import { GathioConfig } from "./lib/config.js";
+import { GathioConfig } from "./lib/config.ts";
+import { EmailService } from "./lib/email.ts";
+import { ExpressHandlebars } from "express-handlebars";
 
 interface Locals {
     config: GathioConfig;
 }
 
-declare module "express" {
-    export interface Response {
-        locals: {
-            config?: GathioConfig;
-        };
+declare global {
+    namespace Express {
+        interface Request extends Express.Request {
+            hbsInstance: ExpressHandlebars;
+            emailService: EmailService;
+        }
     }
-}
+}
\ No newline at end of file
diff --git a/src/lib/config.ts b/src/lib/config.ts
index 003a7142..6642eef8 100644
--- a/src/lib/config.ts
+++ b/src/lib/config.ts
@@ -110,46 +110,46 @@ export const instanceRules = (): InstanceRule[] => {
     rules.push(
         config.general.show_public_event_list
             ? {
-                  text: "Public events and groups are displayed on the homepage",
-                  icon: "fas fa-eye",
-              }
+                text: "Public events and groups are displayed on the homepage",
+                icon: "fas fa-eye",
+            }
             : {
-                  text: "Events and groups can only be accessed by direct link",
-                  icon: "fas fa-eye-slash",
-              },
+                text: "Events and groups can only be accessed by direct link",
+                icon: "fas fa-eye-slash",
+            },
     );
     rules.push(
         config.general.creator_email_addresses?.length
             ? {
-                  text: "Only specific people can create events and groups",
-                  icon: "fas fa-user-check",
-              }
+                text: "Only specific people can create events and groups",
+                icon: "fas fa-user-check",
+            }
             : {
-                  text: "Anyone can create events and groups",
-                  icon: "fas fa-users",
-              },
+                text: "Anyone can create events and groups",
+                icon: "fas fa-users",
+            },
     );
     rules.push(
         config.general.delete_after_days > 0
             ? {
-                  text: `Events are automatically deleted ${config.general.delete_after_days} days after they end`,
-                  icon: "far fa-calendar-times",
-              }
+                text: `Events are automatically deleted ${config.general.delete_after_days} days after they end`,
+                icon: "far fa-calendar-times",
+            }
             : {
-                  text: "Events are permanent, and are never automatically deleted",
-                  icon: "far fa-calendar-check",
-              },
+                text: "Events are permanent, and are never automatically deleted",
+                icon: "far fa-calendar-check",
+            },
     );
     rules.push(
         config.general.is_federated
             ? {
-                  text: "This instance federates with other instances using ActivityPub",
-                  icon: "fas fa-globe",
-              }
+                text: "This instance federates with other instances using ActivityPub",
+                icon: "fas fa-globe",
+            }
             : {
-                  text: "This instance does not federate with other instances",
-                  icon: "fas fa-globe",
-              },
+                text: "This instance does not federate with other instances",
+                icon: "fas fa-globe",
+            },
     );
     return rules;
 };
@@ -179,17 +179,35 @@ export const instanceDescription = (): string => {
     }
 };
 
+let _resolvedConfig: GathioConfig | null = null;
 // Attempt to load our global config. Will stop the app if the config file
 // cannot be read (there's no point trying to continue!)
 export const getConfig = (): GathioConfig => {
+    if (_resolvedConfig) {
+        return _resolvedConfig;
+    }
+
     try {
         const config = toml.parse(
             fs.readFileSync("./config/config.toml", "utf-8"),
         ) as GathioConfig;
-        return {
+        const resolvedConfig = {
             ...defaultConfig,
             ...config,
-        };
+        }
+        if (process.env.CYPRESS || process.env.CI) {
+            config.general.mail_service = "none";
+            console.log(
+                "Running in Cypress or CI, not initializing email service.",
+            );
+        } else if (config.general.mail_service === "none") {
+            console.warn(
+                "You have not configured this Gathio instance to send emails! This means that event creators will not receive emails when their events are created, which means they may end up locked out of editing events. Consider setting up an email service.",
+            );
+        }
+
+        _resolvedConfig = resolvedConfig;
+        return resolvedConfig;
     } catch {
         exitWithError(
             "Configuration file not found! Have you renamed './config/config-example.toml' to './config/config.toml'?",
diff --git a/src/lib/email.ts b/src/lib/email.ts
index 7b7a7a1d..7c7c2dd6 100644
--- a/src/lib/email.ts
+++ b/src/lib/email.ts
@@ -1,13 +1,14 @@
-import { Request } from "express";
 import sgMail from "@sendgrid/mail";
+import sgHelpers from "@sendgrid/helpers";
+import { ExpressHandlebars } from "express-handlebars";
 import nodemailer, { Transporter } from "nodemailer";
-import { getConfig } from "./config.js";
+import { GathioConfig, getConfig } from "./config.js";
 import SMTPTransport from "nodemailer/lib/smtp-transport/index.js";
 import { exitWithError } from "./process.js";
-import { renderTemplate } from "./handlebars.js";
+
 const config = getConfig();
 
-type EmailTemplate =
+type EmailTemplateName =
     | "addEventAttendee"
     | "addEventComment"
     | "createEvent"
@@ -16,58 +17,69 @@ type EmailTemplate =
     | "deleteEvent"
     | "editEvent"
     | "eventGroupUpdated"
+    | "removeEventAttendee"
     | "subscribed"
     | "unattendEvent";
 
-export const initEmailService = async (): Promise<boolean> => {
-    if (process.env.CYPRESS || process.env.CI) {
-        console.log(
-            "Running in Cypress or CI, not initializing email service.",
-        );
-        return false;
-    }
-    switch (config.general.mail_service) {
-        case "sendgrid":
-            if (!config.sendgrid?.api_key) {
-                return exitWithError(
-                    "Sendgrid is configured as the email service, but no API key is provided. Please provide an API key in the config file.",
-                );
-            }
-            sgMail.setApiKey(config.sendgrid.api_key);
-            console.log("Sendgrid is ready to send emails.");
-            return true;
-        case "nodemailer":
-            let nodemailerTransporter:Transporter|undefined = undefined;
-            if (config.nodemailer?.smtp_url) {
-                nodemailerTransporter = nodemailer.createTransport(config.nodemailer?.smtp_url);
-            } else {
-                if (
-                    !config.nodemailer?.smtp_server ||
-                    !config.nodemailer?.smtp_port
-                ) {
+export class EmailService {
+    nodemailerTransporter: Transporter | undefined = undefined;
+    sgMail: typeof sgMail | undefined = undefined;
+    hbs: ExpressHandlebars
+
+    public constructor(config: GathioConfig, hbs: ExpressHandlebars) {
+        this.hbs = hbs;
+        switch (config.general.mail_service) {
+            case "sendgrid": {
+                if (!config.sendgrid?.api_key) {
                     return exitWithError(
-                        "Nodemailer is configured as the email service, but not all required fields are provided. Please provide all required fields in the config file.",
+                        "Sendgrid is configured as the email service, but no API key is provided. Please provide an API key in the config file.",
                     );
                 }
-                const nodemailerConfig = {
-                    host: config.nodemailer?.smtp_server,
-                    port: Number(config.nodemailer?.smtp_port) || 587,
-                    tls: { 
-                        // do not fail on invalid certs
-                        rejectUnauthorized: false,
-                    },
-                } as SMTPTransport.Options;
+                this.sgMail = sgMail;
+                this.sgMail.setApiKey(config.sendgrid.api_key);
+                console.log("Sendgrid is ready to send emails.");
+                break;
+            }
+            case "nodemailer": {
+                if (config.nodemailer?.smtp_url) {
+                    this.nodemailerTransporter = nodemailer.createTransport(
+                        config.nodemailer?.smtp_url,
+                    );
+                } else {
+                    if (
+                        !config.nodemailer?.smtp_server ||
+                        !config.nodemailer?.smtp_port
+                    ) {
+                        return exitWithError(
+                            "Nodemailer is configured as the email service, but not all required fields are provided. Please provide all required fields in the config file.",
+                        );
+                    }
+                    const nodemailerConfig = {
+                        host: config.nodemailer?.smtp_server,
+                        port: Number(config.nodemailer?.smtp_port) || 587,
+                        tls: {
+                            // do not fail on invalid certs
+                            rejectUnauthorized: false,
+                        },
+                    } as SMTPTransport.Options;
 
-                if (config.nodemailer?.smtp_username) {
-                    nodemailerConfig.auth = {
-                        user: config.nodemailer?.smtp_username,
-                        pass: config.nodemailer?.smtp_password
-                    };
+                    if (config.nodemailer?.smtp_username) {
+                        nodemailerConfig.auth = {
+                            user: config.nodemailer?.smtp_username,
+                            pass: config.nodemailer?.smtp_password,
+                        };
+                    }
+                    this.nodemailerTransporter =
+                        nodemailer.createTransport(nodemailerConfig);
                 }
-                nodemailerTransporter = nodemailer.createTransport(nodemailerConfig);
             }
 
-            const nodemailerVerified = await nodemailerTransporter.verify();
+        }
+    }
+
+    public async verify(): Promise<boolean> {
+        if (this.nodemailerTransporter) {
+            const nodemailerVerified = await this.nodemailerTransporter.verify();
             if (nodemailerVerified) {
                 console.log("Nodemailer is ready to send emails.");
                 return true;
@@ -76,68 +88,45 @@ export const initEmailService = async (): Promise<boolean> => {
                     "Error verifying Nodemailer transporter. Please check your Nodemailer configuration.",
                 );
             }
-        case "none":
-        default:
-            console.warn(
-                "You have not configured this Gathio instance to send emails! This means that event creators will not receive emails when their events are created, which means they may end up locked out of editing events. Consider setting up an email service.",
-            );
-            return false;
+        }
+        return true;
     }
-};
 
-export const sendEmail = async (
-    to: string,
-    bcc: string,
-    subject: string,
-    text: string,
-    html?: string,
-): Promise<boolean> => {
-    switch (config.general.mail_service) {
-        case "sendgrid":
+    public async sendEmail({
+        to,
+        bcc,
+        subject,
+        text,
+        html,
+    }: {
+        to: string | string[];
+        bcc?: string | string[];
+        subject: string;
+        text: string;
+        html?: string;
+    }): Promise<boolean> {
+        if (this.sgMail) {
             try {
-                await sgMail.send({
+                await this.sgMail.send({
                     to,
                     bcc,
                     from: config.general.email,
-                    subject: `${config.general.site_name}: ${subject}`,
+                    subject,
                     text,
                     html,
                 });
                 return true;
-            } catch (e: any) {
-                if (e.response) {
-                    console.error(e.response.body);
+            } catch (e: unknown | sgHelpers.classes.ResponseError) {
+                if (e instanceof sgHelpers.classes.ResponseError) {
+                    console.error('sendgrid error', e.response.body);
                 } else {
-                    console.error(e);
+                    console.error('sendgrid error', e);
                 }
                 return false;
             }
-        case "nodemailer":
+        } else if (this.nodemailerTransporter) {
             try {
-                let nodemailerTransporter:Transporter|undefined = undefined;
-                if (config.nodemailer?.smtp_url) {
-                    nodemailerTransporter = nodemailer.createTransport(config.nodemailer?.smtp_url);
-                } else {
-                    const nodemailerConfig = {
-                        host: config.nodemailer?.smtp_server,
-                        port: Number(config.nodemailer?.smtp_port) || 587,
-                    } as SMTPTransport.Options;
-
-                    if (config.nodemailer?.smtp_username) {
-                        nodemailerConfig.auth = {
-                            user: config.nodemailer?.smtp_username,
-                            pass: config.nodemailer?.smtp_password
-                        };
-                    }
-
-                    nodemailerTransporter = nodemailer.createTransport(nodemailerConfig);
-                }
-                await nodemailerTransporter.sendMail({
-                    envelope: {
-                        from: config.general.email,
-                        to,
-                        bcc,
-                    },
+                await this.nodemailerTransporter.sendMail({
                     from: config.general.email,
                     to,
                     bcc,
@@ -150,31 +139,63 @@ export const sendEmail = async (
                 console.error(e);
                 return false;
             }
-        default:
-            return false;
+        } else {
+            // no mailer, so noop
+            return true;
+        }
     }
-};
 
-export const sendEmailFromTemplate = async (
-    to: string,
-    bcc: string,
-    subject: string,
-    template: EmailTemplate,
-    templateData: Record<string, unknown>,
-    req: Request,
-): Promise<boolean> => {
-    const html = await renderTemplate(req, `${template}/${template}Html`, {
-        siteName: config.general.site_name,
-        siteLogo: config.general.email_logo_url,
-        domain: config.general.domain,
-        cache: true,
-        layout: "email.handlebars",
-        ...templateData,
-    });
-    const text = await renderTemplate(
-        req,
-        `${template}/${template}Text`,
-        templateData,
-    );
-    return await sendEmail(to, bcc, subject, text, html);
-};
+    public async sendEmailFromTemplate({
+        to,
+        bcc = "",
+        subject,
+        templateName,
+        templateData = {}
+    }: {
+        to: string | string[];
+        bcc?: string | string[] | undefined;
+        subject: string;
+        templateName: EmailTemplateName;
+        templateData?: object;
+    },
+    ): Promise<boolean> {
+        const [html, text] = await Promise.all([
+            this.hbs.renderView(
+                `./views/emails/${templateName}/${templateName}Html.handlebars`,
+                {
+                    domain: config.general.domain,
+                    contactEmail: config.general.email,
+                    siteName: config.general.site_name,
+                    mailService: config.general.mail_service,
+                    siteLogo: config.general.email_logo_url,
+                    isFederated: config.general.is_federated || true,
+                    cache: true,
+                    layout: "email.handlebars",
+                    ...templateData,
+                }
+            ),
+            this.hbs.renderView(
+                `./views/emails/${templateName}/${templateName}Text.handlebars`,
+                {
+                    domain: config.general.domain,
+                    contactEmail: config.general.email,
+                    siteName: config.general.site_name,
+                    mailService: config.general.mail_service,
+                    siteLogo: config.general.email_logo_url,
+                    isFederated: config.general.is_federated || true,
+                    cache: true,
+                    layout: "email.handlebars",
+                    ...templateData,
+                }
+            ),
+        ]);
+
+        return this.sendEmail({
+            to,
+            bcc,
+            subject: `${config.general.site_name}: ${subject}`,
+            text,
+            html
+        });
+    }
+}
diff --git a/src/lib/handlebars.ts b/src/lib/handlebars.ts
deleted file mode 100644
index d5a8b6e4..00000000
--- a/src/lib/handlebars.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { Request } from "express";
-
-export const renderTemplate = async (
-    req: Request,
-    templateName: string,
-    data: Record<string, unknown>,
-): Promise<string> => {
-    return new Promise<string>((resolve, reject) => {
-        req.app
-            .get("hbsInstance")
-            .renderView(
-                `./views/emails/${templateName}.handlebars`,
-                data,
-                (err: any, html: string) => {
-                    if (err) {
-                        console.error(err);
-                        reject(err);
-                    }
-                    resolve(html);
-                },
-            );
-    });
-};
diff --git a/src/lib/middleware.ts b/src/lib/middleware.ts
index 50731371..69fbe4e9 100644
--- a/src/lib/middleware.ts
+++ b/src/lib/middleware.ts
@@ -1,7 +1,7 @@
 import { NextFunction, Request, Response } from "express";
 import MagicLink from "../models/MagicLink.js";
 import getConfig, { GathioConfig } from "../lib/config.js";
-import { deepMerge } from "../util/object.js";
+import { merge as deepMerge } from "ts-deepmerge";
 
 export const checkMagicLink = async (
     req: Request,
diff --git a/src/routes.js b/src/routes.js
index e758e6b7..d0fd9fcf 100755
--- a/src/routes.js
+++ b/src/routes.js
@@ -9,8 +9,6 @@ import crypto from "crypto";
 import request from "request";
 import niceware from "niceware";
 import ical from "ical";
-import sgMail from "@sendgrid/mail";
-import nodemailer from "nodemailer";
 import fileUpload from "express-fileupload";
 import Jimp from "jimp";
 import schedule from "node-schedule";
@@ -24,14 +22,10 @@ import EventGroup from "./models/EventGroup.js";
 import path from "path";
 import { activityPubContentType } from "./lib/activitypub.js";
 import { hashString } from "./util/generator.js";
-import { initEmailService } from "./lib/email.js";
+import { EmailService } from "./lib/email.js";
 
 const config = getConfig();
 const domain = config.general.domain;
-const contactEmail = config.general.email;
-const siteName = config.general.site_name;
-const mailService = config.general.mail_service;
-const siteLogo = config.general.email_logo_url;
 const isFederated = config.general.is_federated || true;
 
 // This alphabet (used to generate all event, group, etc. IDs) is missing '-'
@@ -42,12 +36,6 @@ const nanoid = customAlphabet(
 );
 
 const router = express.Router();
-
-let sendEmails = false;
-initEmailService().then((emailService) => {
-    sendEmails = emailService
-});
-
 router.use(fileUpload());
 
 // SCHEDULED DELETION
@@ -58,7 +46,10 @@ schedule.scheduleJob("59 23 * * *", function (fireDate) {
         return;
     }
 
-    const too_old = moment.tz("Etc/UTC").subtract(deleteAfterDays, "days").toDate();
+    const too_old = moment
+        .tz("Etc/UTC")
+        .subtract(deleteAfterDays, "days")
+        .toDate();
     console.log(
         "Old event deletion running! Deleting all events concluding before ",
         too_old,
@@ -81,9 +72,9 @@ schedule.scheduleJob("59 23 * * *", function (fireDate) {
                                 "deleteOldEvents",
                                 "error",
                                 "Attempt to delete old event " +
-                                id +
-                                " failed with error: " +
-                                err,
+                                    id +
+                                    " failed with error: " +
+                                    err,
                             );
                         });
                 };
@@ -100,9 +91,9 @@ schedule.scheduleJob("59 23 * * *", function (fireDate) {
                                     "deleteOldEvents",
                                     "error",
                                     "Attempt to delete event image for old event " +
-                                    event.id +
-                                    " failed with error: " +
-                                    err,
+                                        event.id +
+                                        " failed with error: " +
+                                        err,
                                 );
                             }
                             // Image removed
@@ -149,9 +140,9 @@ schedule.scheduleJob("59 23 * * *", function (fireDate) {
                 "deleteOldEvents",
                 "error",
                 "Attempt to delete old event " +
-                event.id +
-                " failed with error: " +
-                err,
+                    event.id +
+                    " failed with error: " +
+                    err,
             );
         });
 
@@ -204,9 +195,9 @@ router.post("/deleteimage/:eventID/:editToken", (req, res) => {
                             "deleteEventImage",
                             "error",
                             "Attempt to delete event image for event " +
-                            req.params.eventID +
-                            " failed with error: " +
-                            err,
+                                req.params.eventID +
+                                " failed with error: " +
+                                err,
                         );
                     }
                     // Image removed
@@ -227,9 +218,9 @@ router.post("/deleteimage/:eventID/:editToken", (req, res) => {
                                 "deleteEventImage",
                                 "error",
                                 "Attempt to delete event image for event " +
-                                req.params.eventID +
-                                " failed with error: " +
-                                err,
+                                    req.params.eventID +
+                                    " failed with error: " +
+                                    err,
                             );
                         });
                 },
@@ -271,9 +262,9 @@ router.post("/deleteevent/:eventID/:editToken", (req, res) => {
                                         "deleteEvent",
                                         "error",
                                         "Attempt to delete event " +
-                                        req.params.eventID +
-                                        " failed with error: " +
-                                        err,
+                                            req.params.eventID +
+                                            " failed with error: " +
+                                            err,
                                     );
                                 }
                             },
@@ -293,9 +284,9 @@ router.post("/deleteevent/:eventID/:editToken", (req, res) => {
                                                     "deleteEvent",
                                                     "error",
                                                     "Attempt to delete event image for event " +
-                                                    req.params.eventID +
-                                                    " failed with error: " +
-                                                    err,
+                                                        req.params.eventID +
+                                                        " failed with error: " +
+                                                        err,
                                                 );
                                             }
                                             // Image removed
@@ -303,8 +294,8 @@ router.post("/deleteevent/:eventID/:editToken", (req, res) => {
                                                 "deleteEvent",
                                                 "success",
                                                 "Event " +
-                                                req.params.eventID +
-                                                " deleted",
+                                                    req.params.eventID +
+                                                    " deleted",
                                             );
                                         },
                                     );
@@ -314,82 +305,44 @@ router.post("/deleteevent/:eventID/:editToken", (req, res) => {
                                 });
                                 res.end();
 
-                                // Send emails here otherwise they don't exist lol
-                                if (sendEmails) {
-                                    const attendeeEmails = event.attendees
-                                        .filter(
-                                            (o) =>
-                                                o.status === "attending" &&
-                                                o.email,
-                                        )
-                                        .map((o) => o.email);
-                                    if (attendeeEmails.length) {
-                                        console.log(
-                                            "Sending emails to: " +
+                                const attendeeEmails = event?.attendees?.filter(
+                                        (o) =>
+                                            o.status === "attending" &&
+                                            o.email,
+                                    )
+                                    .map((o) => o.email || '') || [];
+                                if (attendeeEmails.length) {
+                                    console.log(
+                                        "Sending emails to: " +
                                             attendeeEmails,
-                                        );
-                                        req.app.get("hbsInstance").renderView(
-                                            "./views/emails/deleteEvent/deleteEventHtml.handlebars",
-                                            {
-                                                siteName,
-                                                siteLogo,
-                                                domain,
-                                                eventName: event.name,
-                                                cache: true,
-                                                layout: "email.handlebars",
-                                            },
-                                            function (err, html) {
-                                                const msg = {
-                                                    to: attendeeEmails,
-                                                    from: contactEmail,
-                                                    subject: `${siteName}: ${event.name} was deleted`,
-                                                    html,
-                                                };
-                                                switch (mailService) {
-                                                    case "sendgrid":
-                                                        sgMail
-                                                            .sendMultiple(msg)
-                                                            .catch((e) => {
-                                                                console.error(
-                                                                    e.toString(),
-                                                                );
-                                                                res.status(
-                                                                    500,
-                                                                ).end();
-                                                            });
-                                                        break;
-                                                    case "nodemailer":
-                                                        nodemailerTransporter
-                                                            .sendMail(msg)
-                                                            .catch((e) => {
-                                                                console.error(
-                                                                    e.toString(),
-                                                                );
-                                                                res.status(
-                                                                    500,
-                                                                ).end();
-                                                            });
-                                                        break;
-                                                }
-                                            },
-                                        );
-                                    } else {
-                                        console.log("Nothing to send!");
-                                    }
+                                    );
+                                    req.emailService.sendEmailFromTemplate({
+                                        to: attendeeEmails, 
+                                        subject: `${event?.name} was deleted`,
+                                        templateName: "deleteEvent",
+                                        templateData: {
+                                            eventName: event?.name,
+                                        },
+                                    }).catch((e) => {
+                                        console.error('error sending attendee email', e.toString());
+                                        res.status(500).end();
+                                    });
+                                } else {
+                                    console.log("Nothing to send!");
                                 }
                             })
                             .catch((err) => {
                                 res.send(
                                     "Sorry! Something went wrong (error deleting): " +
-                                    err,
+                                        err,
                                 );
                                 addToLog(
                                     "deleteEvent",
                                     "error",
                                     "Attempt to delete event " +
-                                    req.params.eventID +
-                                    " failed with error: " +
-                                    err,
+                                        req.params.eventID +
+                                        " failed with error: " +
+                                        err,
                                 );
                             });
                     },
@@ -401,8 +354,8 @@ router.post("/deleteevent/:eventID/:editToken", (req, res) => {
                     "deleteEvent",
                     "error",
                     "Attempt to delete event " +
-                    req.params.eventID +
-                    " failed with error: token does not match",
+                        req.params.eventID +
+                        " failed with error: token does not match",
                 );
             }
         })
@@ -412,9 +365,9 @@ router.post("/deleteevent/:eventID/:editToken", (req, res) => {
                 "deleteEvent",
                 "error",
                 "Attempt to delete event " +
-                req.params.eventID +
-                " failed with error: " +
-                err,
+                    req.params.eventID +
+                    " failed with error: " +
+                    err,
             );
         });
 });
@@ -447,9 +400,9 @@ router.post("/deleteeventgroup/:eventGroupID/:editToken", (req, res) => {
                                 "deleteEventGroup",
                                 "error",
                                 "Attempt to delete event group " +
-                                req.params.eventGroupID +
-                                " failed with error: " +
-                                err,
+                                    req.params.eventGroupID +
+                                    " failed with error: " +
+                                    err,
                             );
                         }
                     },
@@ -469,9 +422,9 @@ router.post("/deleteeventgroup/:eventGroupID/:editToken", (req, res) => {
                                             "deleteEventGroup",
                                             "error",
                                             "Attempt to delete event image for event group " +
-                                            req.params.eventGroupID +
-                                            " failed with error: " +
-                                            err,
+                                                req.params.eventGroupID +
+                                                " failed with error: " +
+                                                err,
                                         );
                                     }
                                 },
@@ -487,8 +440,8 @@ router.post("/deleteeventgroup/:eventGroupID/:editToken", (req, res) => {
                                     "deleteEventGroup",
                                     "success",
                                     "Event group " +
-                                    req.params.eventGroupID +
-                                    " deleted",
+                                        req.params.eventGroupID +
+                                        " deleted",
                                 );
                                 res.writeHead(302, {
                                     Location: "/",
@@ -498,30 +451,30 @@ router.post("/deleteeventgroup/:eventGroupID/:editToken", (req, res) => {
                             .catch((err) => {
                                 res.send(
                                     "Sorry! Something went wrong (error deleting): " +
-                                    err,
+                                        err,
                                 );
                                 addToLog(
                                     "deleteEventGroup",
                                     "error",
                                     "Attempt to delete event group " +
-                                    req.params.eventGroupID +
-                                    " failed with error: " +
-                                    err,
+                                        req.params.eventGroupID +
+                                        " failed with error: " +
+                                        err,
                                 );
                             });
                     })
                     .catch((err) => {
                         res.send(
                             "Sorry! Something went wrong (error deleting): " +
-                            err,
+                                err,
                         );
                         addToLog(
                             "deleteEventGroup",
                             "error",
                             "Attempt to delete event group " +
-                            req.params.eventGroupID +
-                            " failed with error: " +
-                            err,
+                                req.params.eventGroupID +
+                                " failed with error: " +
+                                err,
                         );
                     });
             } else {
@@ -531,8 +484,8 @@ router.post("/deleteeventgroup/:eventGroupID/:editToken", (req, res) => {
                     "deleteEventGroup",
                     "error",
                     "Attempt to delete event group " +
-                    req.params.eventGroupID +
-                    " failed with error: token does not match",
+                        req.params.eventGroupID +
+                        " failed with error: token does not match",
                 );
             }
         })
@@ -542,9 +495,9 @@ router.post("/deleteeventgroup/:eventGroupID/:editToken", (req, res) => {
                 "deleteEventGroup",
                 "error",
                 "Attempt to delete event group " +
-                req.params.eventGroupID +
-                " failed with error: " +
-                err,
+                    req.params.eventGroupID +
+                    " failed with error: " +
+                    err,
             );
         });
 });
@@ -562,9 +515,9 @@ router.post("/attendee/provision", async (req, res) => {
             "provisionEventAttendee",
             "error",
             "Attempt to provision attendee in event " +
-            req.query.eventID +
-            " failed with error: " +
-            e,
+                req.query.eventID +
+                " failed with error: " +
+                e,
         );
         return res.sendStatus(500);
     });
@@ -580,9 +533,9 @@ router.post("/attendee/provision", async (req, res) => {
             "provisionEventAttendee",
             "error",
             "Attempt to provision attendee in event " +
-            req.query.eventID +
-            " failed with error: " +
-            e,
+                req.query.eventID +
+                " failed with error: " +
+                e,
         );
         return res.sendStatus(500);
     });
@@ -618,9 +571,9 @@ router.post("/attendevent/:eventID", async (req, res) => {
             "attendEvent",
             "error",
             "Attempt to attend event " +
-            req.params.eventID +
-            " failed with error: " +
-            e,
+                req.params.eventID +
+                " failed with error: " +
+                e,
         );
         return res.sendStatus(500);
     });
@@ -659,56 +612,38 @@ router.post("/attendevent/:eventID", async (req, res) => {
                 "attendees.$.name": req.body.attendeeName,
                 "attendees.$.email": req.body.attendeeEmail,
                 "attendees.$.number": req.body.attendeeNumber,
-                "attendees.$.visibility": !!req.body.attendeeVisible ? "public" : "private",
+                "attendees.$.visibility": req.body.attendeeVisible
+                    ? "public"
+                    : "private",
             },
         },
     )
         .then((event) => {
+            if (!event) {
+                return res.sendStatus(404);
+            }
+
             addToLog(
                 "addEventAttendee",
                 "success",
                 "Attendee added to event " + req.params.eventID,
             );
-            if (sendEmails) {
-                if (req.body.attendeeEmail) {
-                    req.app.get("hbsInstance").renderView(
-                        "./views/emails/addEventAttendee/addEventAttendeeHtml.handlebars",
-                        {
-                            eventID: req.params.eventID,
-                            siteName,
-                            siteLogo,
-                            domain,
-                            removalPassword: req.body.removalPassword,
-                            removalPasswordHash: hashString(req.body.removalPassword),
-                            cache: true,
-                            layout: "email.handlebars",
-                        },
-                        function (err, html) {
-                            const msg = {
-                                to: req.body.attendeeEmail,
-                                from: contactEmail,
-                                subject: `${siteName}: You're RSVPed to ${event.name}`,
-                                html,
-                            };
-                            switch (mailService) {
-                                case "sendgrid":
-                                    sgMail.send(msg).catch((e) => {
-                                        console.error(e.toString());
-                                        res.status(500).end();
-                                    });
-                                    break;
-                                case "nodemailer":
-                                    nodemailerTransporter
-                                        .sendMail(msg)
-                                        .catch((e) => {
-                                            console.error(e.toString());
-                                            res.status(500).end();
-                                        });
-                                    break;
-                            }
-                        },
-                    );
-                }
+            if (req.body.attendeeEmail) {          
+                req.emailService.sendEmailFromTemplate({
+                    to: req.body.attendeeEmail,
+                    subject: `You're RSVPed to ${event.name}`,
+                    templateName: "addEventAttendee",
+                    templateData:{
+                        eventID: req.params.eventID,
+                        removalPassword: req.body.removalPassword,
+                        removalPasswordHash: hashString(
+                            req.body.removalPassword,
+                        ),
+                    },
+                }).catch((e) => {
+                    console.error('error sending addEventAttendee email', e.toString());
+                    res.status(500).end();
+                });
             }
             res.redirect(`/${req.params.eventID}`);
         })
@@ -718,9 +653,9 @@ router.post("/attendevent/:eventID", async (req, res) => {
                 "addEventAttendee",
                 "error",
                 "Attempt to add attendee to event " +
-                req.params.eventID +
-                " failed with error: " +
-                error,
+                    req.params.eventID +
+                    " failed with error: " +
+                    error,
             );
         });
 });
@@ -737,54 +672,32 @@ router.get("/oneclickunattendevent/:eventID/:attendeeID", (req, res) => {
     ) {
         return res.sendStatus(200);
     }
-    Event.updateOne(
+    Event.findOneAndUpdate(
         { id: req.params.eventID },
         { $pull: { attendees: { _id: req.params.attendeeID } } },
     )
-        .then((response) => {
+        .then((event) => {
+            if (!event) {
+                return res.sendStatus(404);
+            }
             addToLog(
                 "oneClickUnattend",
                 "success",
                 "Attendee removed via one click unattend " + req.params.eventID,
             );
-            if (sendEmails) {
-                // currently this is never called because we don't have the email address
-                if (req.body.attendeeEmail) {
-                    req.app.get("hbsInstance").renderView(
-                        "./views/emails/removeEventAttendee/removeEventAttendeeHtml.handlebars",
-                        {
-                            eventName: req.params.eventName,
-                            siteName,
-                            domain,
-                            cache: true,
-                            layout: "email.handlebars",
-                        },
-                        function (err, html) {
-                            const msg = {
-                                to: req.body.attendeeEmail,
-                                from: contactEmail,
-                                subject: `${siteName}: You have been removed from an event`,
-                                html,
-                            };
-                            switch (mailService) {
-                                case "sendgrid":
-                                    sgMail.send(msg).catch((e) => {
-                                        console.error(e.toString());
-                                        res.status(500).end();
-                                    });
-                                    break;
-                                case "nodemailer":
-                                    nodemailerTransporter
-                                        .sendMail(msg)
-                                        .catch((e) => {
-                                            console.error(e.toString());
-                                            res.status(500).end();
-                                        });
-                                    break;
-                            }
-                        },
-                    );
-                }
+            // currently this is never called because we don't have the email address
+            if (req.body.attendeeEmail) {
+                req.emailService.sendEmailFromTemplate({
+                    to: req.body.attendeeEmail,
+                    subject: `You have been removed from an event`,
+                    templateName: "removeEventAttendee",
+                    templateData:{
+                        eventName: event.name,
+                    },
+                }).catch((e) => {
+                    console.error('error sending removeEventAttendeeHtml email', e.toString());
+                    res.status(500).end();
+                });
             }
             res.writeHead(302, {
                 Location: "/" + req.params.eventID,
@@ -797,63 +710,40 @@ router.get("/oneclickunattendevent/:eventID/:attendeeID", (req, res) => {
                 "removeEventAttendee",
                 "error",
                 "Attempt to remove attendee by admin from event " +
-                req.params.eventID +
-                " failed with error: " +
-                err,
+                    req.params.eventID +
+                    " failed with error: " +
+                    err,
             );
         });
 });
 
 router.post("/removeattendee/:eventID/:attendeeID", (req, res) => {
-    Event.updateOne(
+    Event.findOneAndUpdate(
         { id: req.params.eventID },
         { $pull: { attendees: { _id: req.params.attendeeID } } },
     )
-        .then((response) => {
+        .then((event) => {
+            if (!event) {
+                return res.sendStatus(404);
+            }
             addToLog(
                 "removeEventAttendee",
                 "success",
                 "Attendee removed by admin from event " + req.params.eventID,
             );
-            if (sendEmails) {
-                // currently this is never called because we don't have the email address
-                if (req.body.attendeeEmail) {
-                    req.app.get("hbsInstance").renderView(
-                        "./views/emails/removeEventAttendee/removeEventAttendeeHtml.handlebars",
-                        {
-                            eventName: req.params.eventName,
-                            siteName,
-                            siteLogo,
-                            domain,
-                            cache: true,
-                            layout: "email.handlebars",
-                        },
-                        function (err, html) {
-                            const msg = {
-                                to: req.body.attendeeEmail,
-                                from: contactEmail,
-                                subject: `${siteName}: You have been removed from an event`,
-                                html,
-                            };
-                            switch (mailService) {
-                                case "sendgrid":
-                                    sgMail.send(msg).catch((e) => {
-                                        console.error(e.toString());
-                                        res.status(500).end();
-                                    });
-                                    break;
-                                case "nodemailer":
-                                    nodemailerTransporter
-                                        .sendMail(msg)
-                                        .catch((e) => {
-                                            console.error(e.toString());
-                                            res.status(500).end();
-                                        });
-                                    break;
-                            }
-                        },
-                    );
-                }
+            // currently this is never called because we don't have the email address
+            if (req.body.attendeeEmail) {
+                req.emailService.sendEmailFromTemplate({
+                    to: req.body.attendeeEmail, 
+                    subject: `You have been removed from an event`, 
+                    templateName: "removeEventAttendee",
+                    templateData: {
+                        eventName: event.name,
+                    },
+                }).catch((e) => {
+                    console.error('error sending removeEventAttendeeHtml email', e.toString());
+                    res.status(500).end();                  
+                });
             }
             res.writeHead(302, {
                 Location: "/" + req.params.eventID,
@@ -866,9 +756,9 @@ router.post("/removeattendee/:eventID/:attendeeID", (req, res) => {
                 "removeEventAttendee",
                 "error",
                 "Attempt to remove attendee by admin from event " +
-                req.params.eventID +
-                " failed with error: " +
-                err,
+                    req.params.eventID +
+                    " failed with error: " +
+                    err,
             );
         });
 });
@@ -893,45 +783,20 @@ router.post("/subscribe/:eventGroupID", (req, res) => {
             }
             eventGroup.subscribers.push(subscriber);
             eventGroup.save();
-            if (sendEmails) {
-                req.app.get("hbsInstance").renderView(
-                    "./views/emails/subscribed/subscribedHtml.handlebars",
-                    {
-                        eventGroupName: eventGroup.name,
-                        eventGroupID: eventGroup.id,
-                        emailAddress: encodeURIComponent(subscriber.email),
-                        siteName,
-                        siteLogo,
-                        domain,
-                        cache: true,
-                        layout: "email.handlebars",
-                    },
-                    function (err, html) {
-                        const msg = {
-                            to: subscriber.email,
-                            from: contactEmail,
-                            subject: `${siteName}: You have subscribed to an event group`,
-                            html,
-                        };
-                        switch (mailService) {
-                            case "sendgrid":
-                                sgMail.send(msg).catch((e) => {
-                                    console.error(e.toString());
-                                    res.status(500).end();
-                                });
-                                break;
-                            case "nodemailer":
-                                nodemailerTransporter
-                                    .sendMail(msg)
-                                    .catch((e) => {
-                                        console.error(e.toString());
-                                        res.status(500).end();
-                                    });
-                                break;
-                        }
-                    },
-                );
-            }
+            req.emailService.sendEmailFromTemplate({
+                to: subscriber.email, 
+                subject: "You have subscribed to an event group",
+                templateName: "subscribed",
+                templateData:{
+                    eventGroupName: eventGroup.name,
+                    eventGroupID: eventGroup.id,
+                    emailAddress: encodeURIComponent(subscriber.email),
+                },
+            }).catch((e) => {
+                console.error('error sending removeEventAttendeeHtml email', e.toString());
+                res.status(500).end();                  
+            });
+
             return res.redirect(`/group/${eventGroup.id}`);
         })
         .catch((error) => {
@@ -939,11 +804,11 @@ router.post("/subscribe/:eventGroupID", (req, res) => {
                 "addSubscription",
                 "error",
                 "Attempt to subscribe " +
-                req.body.emailAddress +
-                " to event group " +
-                req.params.eventGroupID +
-                " failed with error: " +
-                error,
+                    req.body.emailAddress +
+                    " to event group " +
+                    req.params.eventGroupID +
+                    " failed with error: " +
+                    error,
             );
             return res.sendStatus(500);
         });
@@ -970,11 +835,11 @@ router.get("/unsubscribe/:eventGroupID", (req, res) => {
                 "removeSubscription",
                 "error",
                 "Attempt to unsubscribe " +
-                req.query.email +
-                " from event group " +
-                req.params.eventGroupID +
-                " failed with error: " +
-                error,
+                    req.query.email +
+                    " from event group " +
+                    req.params.eventGroupID +
+                    " failed with error: " +
+                    error,
             );
             return res.sendStatus(500);
         });
@@ -994,7 +859,9 @@ router.post("/post/comment/:eventID", (req, res) => {
             id: req.params.eventID,
         },
         function (err, event) {
-            if (!event) return;
+            if (!event) {
+                return res.sendStatus(404);
+            }
             event.comments.push(newComment);
             event
                 .save()
@@ -1020,72 +887,40 @@ router.post("/post/comment/:eventID", (req, res) => {
                         event.followers,
                         req.params.eventID,
                     );
-                    if (sendEmails) {
-                        Event.findOne({ id: req.params.eventID }).then(
-                            (event) => {
-                                const attendeeEmails = event.attendees
-                                    .filter(
-                                        (o) =>
-                                            o.status === "attending" && o.email,
-                                    )
-                                    .map((o) => o.email);
-                                if (attendeeEmails.length) {
-                                    console.log(
-                                        "Sending emails to: " + attendeeEmails,
-                                    );
-                                    req.app.get("hbsInstance").renderView(
-                                        "./views/emails/addEventComment/addEventCommentHtml.handlebars",
-                                        {
-                                            siteName,
-                                            siteLogo,
-                                            domain,
-                                            eventID: req.params.eventID,
-                                            commentAuthor:
-                                                req.body.commentAuthor,
-                                            cache: true,
-                                            layout: "email.handlebars",
-                                        },
-                                        function (err, html) {
-                                            const msg = {
-                                                to: attendeeEmails,
-                                                from: contactEmail,
-                                                subject: `${siteName}: New comment in ${event.name}`,
-                                                html,
-                                            };
-                                            switch (mailService) {
-                                                case "sendgrid":
-                                                    sgMail
-                                                        .sendMultiple(msg)
-                                                        .catch((e) => {
-                                                            console.error(
-                                                                e.toString(),
-                                                            );
-                                                            res.status(
-                                                                500,
-                                                            ).end();
-                                                        });
-                                                    break;
-                                                case "nodemailer":
-                                                    nodemailerTransporter
-                                                        .sendMail(msg)
-                                                        .catch((e) => {
-                                                            console.error(
-                                                                e.toString(),
-                                                            );
-                                                            res.status(
-                                                                500,
-                                                            ).end();
-                                                        });
-                                                    break;
-                                            }
-                                        },
-                                    );
-                                } else {
-                                    console.log("Nothing to send!");
-                                }
-                            },
-                        );
+                    if (!event) {
+                        return res.sendStatus(404);
                     }
+                    
+                    Event.findOne({ id: req.params.eventID }).then(
+                        (event) => {
+                            const attendeeEmails = event.attendees
+                                .filter(
+                                    (o) =>
+                                        o.status === "attending" && o.email,
+                                )
+                                .map((o) => o.email || '')  || [];
+                            if (attendeeEmails.length) {
+                                console.log(
+                                    "Sending emails to: " + attendeeEmails,
+                                );
+                                req.emailService.sendEmailFromTemplate({
+                                    to: event?.creatorEmail || config.general.email,
+                                    bcc: attendeeEmails,
+                                    subject: `New comment in ${event.name}`,
+                                    templateName: "addEventComment",
+                                    templateData:{
+                                        eventID: req.params.eventID,
+                                        commentAuthor: req.body.commentAuthor,
+                                    },
+                                }).catch((e) => {
+                                    console.error('error sending removeEventAttendeeHtml email', e.toString());
+                                    res.status(500).end();                  
+                                });
+                            } else {
+                                console.log("Nothing to send!");
+                            }
+                        },
+                    );
                     res.writeHead(302, {
                         Location: "/" + req.params.eventID,
                     });
@@ -1097,9 +932,9 @@ router.post("/post/comment/:eventID", (req, res) => {
                         "addEventComment",
                         "error",
                         "Attempt to add comment to event " +
-                        req.params.eventID +
-                        " failed with error: " +
-                        err,
+                            req.params.eventID +
+                            " failed with error: " +
+                            err,
                     );
                 });
         },
@@ -1120,7 +955,9 @@ router.post("/post/reply/:eventID/:commentID", (req, res) => {
             id: req.params.eventID,
         },
         function (err, event) {
-            if (!event) return;
+            if (!event) {
+                return res.sendStatus(404);
+            }
             var parentComment = event.comments.id(commentID);
             parentComment.replies.push(newReply);
             event
@@ -1130,9 +967,9 @@ router.post("/post/reply/:eventID/:commentID", (req, res) => {
                         "addEventReply",
                         "success",
                         "Reply added to comment " +
-                        commentID +
-                        " in event " +
-                        req.params.eventID,
+                            commentID +
+                            " in event " +
+                            req.params.eventID,
                     );
                     // broadcast an identical message to all followers, will show in their home timeline
                     const guidObject = crypto.randomBytes(16).toString("hex");
@@ -1149,71 +986,39 @@ router.post("/post/reply/:eventID/:commentID", (req, res) => {
                         event.followers,
                         req.params.eventID,
                     );
-                    if (sendEmails) {
-                        Event.findOne({ id: req.params.eventID }).then(
-                            (event) => {
-                                const attendeeEmails = event.attendees
-                                    .filter(
-                                        (o) =>
-                                            o.status === "attending" && o.email,
-                                    )
-                                    .map((o) => o.email);
-                                if (attendeeEmails.length) {
-                                    console.log(
-                                        "Sending emails to: " + attendeeEmails,
-                                    );
-                                    req.app.get("hbsInstance").renderView(
-                                        "./views/emails/addEventComment/addEventCommentHtml.handlebars",
-                                        {
-                                            siteName,
-                                            siteLogo,
-                                            domain,
-                                            eventID: req.params.eventID,
-                                            commentAuthor: req.body.replyAuthor,
-                                            cache: true,
-                                            layout: "email.handlebars",
-                                        },
-                                        function (err, html) {
-                                            const msg = {
-                                                to: attendeeEmails,
-                                                from: contactEmail,
-                                                subject: `${siteName}: New comment in ${event.name}`,
-                                                html,
-                                            };
-                                            switch (mailService) {
-                                                case "sendgrid":
-                                                    sgMail
-                                                        .sendMultiple(msg)
-                                                        .catch((e) => {
-                                                            console.error(
-                                                                e.toString(),
-                                                            );
-                                                            res.status(
-                                                                500,
-                                                            ).end();
-                                                        });
-                                                    break;
-                                                case "nodemailer":
-                                                    nodemailerTransporter
-                                                        .sendMail(msg)
-                                                        .catch((e) => {
-                                                            console.error(
-                                                                e.toString(),
-                                                            );
-                                                            res.status(
-                                                                500,
-                                                            ).end();
-                                                        });
-                                                    break;
-                                            }
-                                        },
-                                    );
-                                } else {
-                                    console.log("Nothing to send!");
-                                }
-                            },
-                        );
-                    }
+                    Event.findOne({ id: req.params.eventID }).then(
+                        (event) => {
+                            if (!event) {
+                                return res.sendStatus(404);
+                            }
+                            const attendeeEmails = event.attendees
+                                .filter(
+                                    (o) =>
+                                        o.status === "attending" && o.email,
+                                )
+                                .map((o) => o.email || '') || [];
+                            if (attendeeEmails.length) {
+                                console.log(
+                                    "Sending emails to: " + attendeeEmails,
+                                );
+                                req.emailService.sendEmailFromTemplate({
+                                    to: event?.creatorEmail || config.general.email,
+                                    bcc: attendeeEmails,
+                                    subject: `New comment in ${event.name}`,
+                                    templateName: "addEventComment",
+                                    templateData: {
+                                        eventID: req.params.eventID,
+                                        commentAuthor: req.body.replyAuthor,
+                                    },
+                                }).catch((e) => {
+                                    console.error('error sending removeEventAttendeeHtml email', e.toString());
+                                    res.status(500).end();                  
+                                });
+                            } else {
+                                console.log("Nothing to send!");
+                            }
+                        },
+                    );
                     res.writeHead(302, {
                         Location: "/" + req.params.eventID,
                     });
@@ -1225,11 +1030,11 @@ router.post("/post/reply/:eventID/:commentID", (req, res) => {
                         "addEventReply",
                         "error",
                         "Attempt to add reply to comment " +
-                        commentID +
-                        " in event " +
-                        req.params.eventID +
-                        " failed with error: " +
-                        err,
+                            commentID +
+                            " in event " +
+                            req.params.eventID +
+                            " failed with error: " +
+                            err,
                     );
                 });
         },
@@ -1265,17 +1070,17 @@ router.post("/deletecomment/:eventID/:commentID/:editToken", (req, res) => {
                     .catch((err) => {
                         res.send(
                             "Sorry! Something went wrong (error deleting): " +
-                            err,
+                                err,
                         );
                         addToLog(
                             "deleteComment",
                             "error",
                             "Attempt to delete comment " +
-                            req.params.commentID +
-                            "from event " +
-                            req.params.eventID +
-                            " failed with error: " +
-                            err,
+                                req.params.commentID +
+                                "from event " +
+                                req.params.eventID +
+                                " failed with error: " +
+                                err,
                         );
                     });
             } else {
@@ -1285,10 +1090,10 @@ router.post("/deletecomment/:eventID/:commentID/:editToken", (req, res) => {
                     "deleteComment",
                     "error",
                     "Attempt to delete comment " +
-                    req.params.commentID +
-                    "from event " +
-                    req.params.eventID +
-                    " failed with error: token does not match",
+                        req.params.commentID +
+                        "from event " +
+                        req.params.eventID +
+                        " failed with error: token does not match",
                 );
             }
         })
@@ -1298,11 +1103,11 @@ router.post("/deletecomment/:eventID/:commentID/:editToken", (req, res) => {
                 "deleteComment",
                 "error",
                 "Attempt to delete comment " +
-                req.params.commentID +
-                "from event " +
-                req.params.eventID +
-                " failed with error: " +
-                err,
+                    req.params.commentID +
+                    "from event " +
+                    req.params.eventID +
+                    " failed with error: " +
+                    err,
             );
         });
 });
diff --git a/src/routes/event.ts b/src/routes/event.ts
index de5cb4c8..ee45d966 100644
--- a/src/routes/event.ts
+++ b/src/routes/event.ts
@@ -22,14 +22,13 @@ import {
     updateActivityPubActor,
     updateActivityPubEvent,
 } from "../activitypub.js";
-import { sendEmailFromTemplate } from "../lib/email.js";
 import crypto from "crypto";
 import ical from "ical";
 import { markdownToSanitizedHTML } from "../util/markdown.js";
 import { checkMagicLink, getConfigMiddleware } from "../lib/middleware.js";
 import { getConfig } from "../lib/config.js";
-const config = getConfig();
 
+const config = getConfig();
 
 const storage = multer.memoryStorage();
 // Accept only JPEG, GIF or PNG images, up to 10MB
@@ -80,8 +79,8 @@ router.post(
             });
         }
 
-        let eventID = generateEventID();
-        let editToken = generateEditToken();
+        const eventID = generateEventID();
+        const editToken = generateEditToken();
         let eventImageFilename;
         let isPartOfEventGroup = false;
 
@@ -125,7 +124,7 @@ router.post(
         }
 
         // generate RSA keypair for ActivityPub
-        let { publicKey, privateKey } = generateRSAKeypair();
+        const { publicKey, privateKey } = generateRSAKeypair();
 
         const event = new Event({
             id: eventID,
@@ -193,25 +192,20 @@ router.post(
             const savedEvent = await event.save();
             addToLog("createEvent", "success", "Event " + eventID + "created");
             // Send email with edit link
-            if (eventData.creatorEmail && req.app.locals.sendEmails) {
-                sendEmailFromTemplate(
-                    eventData.creatorEmail,
-                    "",
-                    `${eventData.eventName}`,
-                    "createEvent",
-                    {
+            if (eventData.creatorEmail) {
+                req.emailService.sendEmailFromTemplate({
+                    to: eventData.creatorEmail,
+                    subject: eventData.eventName,
+                    templateName: "createEvent",
+                    templateData: {
                         eventID,
                         editToken,
-                        siteName: res.locals.config?.general.site_name,
-                        siteLogo: res.locals.config?.general.email_logo_url,
-                        domain: res.locals.config?.general.domain,
-                    },
-                    req,
-                );
+                    }
+                });
             }
             // If the event was added to a group, send an email to any group
             // subscribers
-            if (event.eventGroup && req.app.locals.sendEmails) {
+            if (event.eventGroup) {
                 try {
                     const eventGroup = await EventGroup.findOne({
                         _id: event.eventGroup.toString(),
@@ -231,24 +225,18 @@ router.post(
                         [] as string[],
                     );
                     subscribers?.forEach((emailAddress) => {
-                        sendEmailFromTemplate(
-                            emailAddress,
-                            "",
-                            `New event in ${eventGroup.name}`,
-                            "eventGroupUpdated",
-                            {
-                                siteName: res.locals.config?.general.site_name,
-                                siteLogo:
-                                    res.locals.config?.general.email_logo_url,
-                                domain: res.locals.config?.general.domain,
+                        req.emailService.sendEmailFromTemplate({
+                            to: emailAddress,
+                            subject: `New event in ${eventGroup.name}`,
+                            templateName: "eventGroupUpdated",
+                            templateData: {
                                 eventGroupName: eventGroup.name,
                                 eventName: event.name,
                                 eventID: event.id,
                                 eventGroupID: eventGroup.id,
                                 emailAddress: encodeURIComponent(emailAddress),
-                            },
-                            req,
-                        );
+                            }
+                        });
                     });
                 } catch (err) {
                     console.error(err);
@@ -256,7 +244,7 @@ router.post(
                         "createEvent",
                         "error",
                         "Attempt to send event group emails failed with error: " +
-                            err,
+                        err,
                     );
                 }
             }
@@ -332,7 +320,7 @@ router.put(
             }
             // Token matches
             // If there is a new image, upload that first
-            let eventID = req.params.eventID;
+            const eventID = req.params.eventID;
             let eventImageFilename = event.image;
             if (req.file?.buffer) {
                 Jimp.read(req.file.buffer)
@@ -388,24 +376,24 @@ router.put(
                 eventGroup: isPartOfEventGroup ? eventGroup?._id : null,
                 activityPubActor: event.activityPubActor
                     ? updateActivityPubActor(
-                          JSON.parse(event.activityPubActor),
-                          eventData.eventDescription,
-                          eventData.eventName,
-                          eventData.eventLocation,
-                          eventImageFilename,
-                          startUTC,
-                          endUTC,
-                          eventData.timezone,
-                      )
+                        JSON.parse(event.activityPubActor),
+                        eventData.eventDescription,
+                        eventData.eventName,
+                        eventData.eventLocation,
+                        eventImageFilename,
+                        startUTC,
+                        endUTC,
+                        eventData.timezone,
+                    )
                     : undefined,
                 activityPubEvent: event.activityPubEvent
                     ? updateActivityPubEvent(
-                          JSON.parse(event.activityPubEvent),
-                          eventData.eventName,
-                          startUTC,
-                          endUTC,
-                          eventData.timezone,
-                      )
+                        JSON.parse(event.activityPubEvent),
+                        eventData.eventName,
+                        startUTC,
+                        endUTC,
+                        eventData.timezone,
+                    )
                     : undefined,
             };
             let diffText =
@@ -452,7 +440,7 @@ router.put(
                 "Event " + req.params.eventID + " edited",
             );
             // send update to ActivityPub subscribers
-            let attendees = updatedEventObject.attendees?.filter((el) => el.id);
+            const attendees = updatedEventObject.attendees?.filter((el) => el.id);
             // broadcast an identical message to all followers, will show in home timeline
             const guidObject = crypto.randomBytes(16).toString("hex");
             const jsonObject = {
@@ -492,26 +480,20 @@ router.put(
                 }
             }
             // Send update to all attendees
-            if (req.app.locals.sendEmails) {
-                const attendeeEmails = event.attendees
-                    ?.filter((o) => o.status === "attending" && o.email)
-                    .map((o) => o.email);
-                if (attendeeEmails?.length) {
-                    sendEmailFromTemplate(
-                        config.general.email,
-                        attendeeEmails.join(","),
-                        `${event.name} was just edited`,
-                        "editEvent",
-                        {
-                            diffText,
-                            eventID: req.params.eventID,
-                            siteName: res.locals.config?.general.site_name,
-                            siteLogo: res.locals.config?.general.email_logo_url,
-                            domain: res.locals.config?.general.domain,
-                        },
-                        req,
-                    );
-                }
+            const attendeeEmails = event.attendees
+                ?.filter((o) => o.status === "attending" && o.email)
+                .map((o) => o.email!);
+            if (attendeeEmails?.length) {
+                req.emailService.sendEmailFromTemplate({
+                    to: config.general.email,
+                    bcc: attendeeEmails,
+                    subject: `${event.name} was just edited`,
+                    templateName: "editEvent",
+                    templateData: {
+                        diffText,
+                        eventID: req.params.eventID,
+                    },
+                });
             }
             res.sendStatus(200);
         } catch (err) {
@@ -520,9 +502,9 @@ router.put(
                 "editEvent",
                 "error",
                 "Attempt to edit event " +
-                    req.params.eventID +
-                    " failed with error: " +
-                    err,
+                req.params.eventID +
+                " failed with error: " +
+                err,
             );
             return res.status(500).json({
                 errors: [
@@ -550,12 +532,12 @@ router.post(
             });
         }
 
-        let eventID = generateEventID();
-        let editToken = generateEditToken();
+        const eventID = generateEventID();
+        const editToken = generateEditToken();
 
-        let iCalObject = ical.parseICS(req.file.buffer.toString("utf8"));
+        const iCalObject = ical.parseICS(req.file.buffer.toString("utf8"));
 
-        let importedEventData = iCalObject[Object.keys(iCalObject)[0]];
+        const importedEventData = iCalObject[Object.keys(iCalObject)[0]];
 
         let creatorEmail: string | undefined;
         if (req.body.creatorEmail) {
@@ -611,21 +593,16 @@ router.post(
             await event.save();
             addToLog("createEvent", "success", `Event ${eventID} created`);
             // Send email with edit link
-            if (creatorEmail && req.app.locals.sendEmails) {
-                sendEmailFromTemplate(
-                    creatorEmail,
-                    "",
-                    `${importedEventData.summary}`,
-                    "createEvent",
-                    {
+            if (creatorEmail) {
+                req.emailService.sendEmailFromTemplate({
+                    to: creatorEmail,
+                    subject: importedEventData.summary || "",
+                    templateName: "createEvent",
+                    templateData: {
                         eventID,
                         editToken,
-                        siteName: res.locals.config?.general.site_name,
-                        siteLogo: res.locals.config?.general.email_logo_url,
-                        domain: res.locals.config?.general.domain,
                     },
-                    req,
-                );
+                });
             }
             return res.json({
                 eventID: eventID,
@@ -692,20 +669,15 @@ router.delete(
                 "success",
                 `Attendee removed self from event ${req.params.eventID}`,
             );
-            if (attendeeEmail && req.app.locals.sendEmails) {
-                await sendEmailFromTemplate(
-                    attendeeEmail,
-                    "",
-                    "You have been removed from an event",
-                    "unattendEvent",
-                    {
+            if (attendeeEmail) {
+                await req.emailService.sendEmailFromTemplate({
+                    to: attendeeEmail,
+                    subject: "You have been removed from an event",
+                    templateName: "unattendEvent",
+                    templateData: {
                         eventID: req.params.eventID,
-                        siteName: res.locals.config?.general.site_name,
-                        siteLogo: res.locals.config?.general.email_logo_url,
-                        domain: res.locals.config?.general.domain,
                     },
-                    req,
-                );
+                });
             }
             res.sendStatus(200);
         } catch (e) {
@@ -744,20 +716,15 @@ router.get(
         );
         await event.save();
         // Send email to the attendee
-        if (req.app.locals.sendEmails && attendee.email) {
-            sendEmailFromTemplate(
-                attendee.email,
-                "",
-                `You have been removed from ${event.name}`,
-                "unattendEvent",
-                {
+        if (attendee.email) {
+            req.emailService.sendEmailFromTemplate({
+                to: attendee.email,
+                subject: `You have been removed from ${event.name}`,
+                templateName: "unattendEvent",
+                templateData: {
                     event,
-                    siteName: res.locals.config?.general.site_name,
-                    siteLogo: res.locals.config?.general.email_logo_url,
-                    domain: res.locals.config?.general.domain,
                 },
-                req,
-            );
+            });
         }
         return res.redirect(`/${req.params.eventID}?m=unattend`);
     },
diff --git a/src/routes/frontend.ts b/src/routes/frontend.ts
index 14bb7794..1b957630 100644
--- a/src/routes/frontend.ts
+++ b/src/routes/frontend.ts
@@ -1,5 +1,4 @@
 import { Router, Request, Response } from "express";
-import fs from "fs";
 import moment from "moment-timezone";
 import { marked } from "marked";
 import { markdownToSanitizedHTML, renderPlain } from "../util/markdown.js";
@@ -25,7 +24,7 @@ const router = Router();
 // Add config middleware to all routes
 router.use(getConfigMiddleware);
 
-router.get("/", (_: Request, res: Response) => {
+router.get("/", (_, res) => {
     if (res.locals.config?.general.show_public_event_list) {
         return res.redirect("/events");
     }
@@ -44,7 +43,7 @@ router.get("/about", (_: Request, res: Response) => {
     });
 });
 
-router.get("/new", (req: Request, res: Response) => {
+router.get("/new", (_: Request, res: Response) => {
     if (res.locals.config?.general.creator_email_addresses?.length) {
         return res.render("createEventMagicLink", frontendConfig(res));
     }
diff --git a/src/routes/group.ts b/src/routes/group.ts
index 9f4105c8..cc53976d 100644
--- a/src/routes/group.ts
+++ b/src/routes/group.ts
@@ -5,7 +5,6 @@ import { validateGroupData } from "../util/validation.js";
 import Jimp from "jimp";
 import { addToLog } from "../helpers.js";
 import EventGroup from "../models/EventGroup.js";
-import { sendEmailFromTemplate } from "../lib/email.js";
 import { marked } from "marked";
 import { renderPlain } from "../util/markdown.js";
 import { checkMagicLink, getConfigMiddleware } from "../lib/middleware.js";
@@ -92,21 +91,16 @@ router.post(
             );
 
             // Send email with edit link
-            if (groupData.creatorEmail && req.app.locals.sendEmails) {
-                sendEmailFromTemplate(
-                    groupData.creatorEmail,
-                    "",
-                    `${eventGroup.name}`,
-                    "createEventGroup",
-                    {
+            if (groupData.creatorEmail) {
+                req.emailService.sendEmailFromTemplate({
+                    to: groupData.creatorEmail,
+                    subject: eventGroup.name,
+                    templateName: "createEventGroup",
+                    templateData: {
                         eventGroupID: eventGroup.id,
                         editToken: eventGroup.editToken,
-                        siteName: res.locals.config?.general.site_name,
-                        siteLogo: res.locals.config?.general.email_logo_url,
-                        domain: res.locals.config?.general.domain,
                     },
-                    req,
-                );
+                });
             }
 
             res.status(200).json({
@@ -182,7 +176,7 @@ router.put(
             }
             // Token matches
             // If there is a new image, upload that first
-            let eventGroupID = req.params.eventGroupID;
+            const eventGroupID = req.params.eventGroupID;
             let eventGroupImageFilename = eventGroup.image;
             if (req.file?.buffer) {
                 Jimp.read(req.file.buffer)
@@ -228,9 +222,9 @@ router.put(
                 "editEventGroup",
                 "error",
                 "Attempt to edit event group " +
-                    req.params.eventGroupID +
-                    " failed with error: " +
-                    err,
+                req.params.eventGroupID +
+                " failed with error: " +
+                err,
             );
             return res.status(500).json({
                 errors: [
diff --git a/src/routes/magicLink.ts b/src/routes/magicLink.ts
index b4afca64..e0a6310b 100644
--- a/src/routes/magicLink.ts
+++ b/src/routes/magicLink.ts
@@ -1,6 +1,5 @@
 import { Router, Request, Response } from "express";
 import { frontendConfig } from "../lib/config.js";
-import { sendEmailFromTemplate } from "../lib/email.js";
 import { generateMagicLinkToken } from "../util/generator.js";
 import MagicLink from "../models/MagicLink.js";
 import { getConfigMiddleware } from "../lib/middleware.js";
@@ -48,19 +47,14 @@ router.post("/magic-link/event/create", async (req: Request, res: Response) => {
     // Take this opportunity to delete any expired magic links
     await MagicLink.deleteMany({ expiryTime: { $lt: new Date() } });
 
-    sendEmailFromTemplate(
-        email,
-        "",
-        `Magic link to create an event`,
-        "createEventMagicLink",
-        {
-            token,
-            siteName: res.locals.config?.general.site_name,
-            siteLogo: res.locals.config?.general.email_logo_url,
-            domain: res.locals.config?.general.domain,
+    req.emailService.sendEmailFromTemplate({
+        to: email,
+        subject: "Magic link to create an event",
+        templateName: "createEventMagicLink",
+        templateData: {
+            token
         },
-        req,
-    );
+    });
     res.render("createEventMagicLink", {
         ...frontendConfig(res),
         message: {
diff --git a/src/util/object.ts b/src/util/object.ts
deleted file mode 100644
index 1ecc89b9..00000000
--- a/src/util/object.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * Simple object check.
- */
-export function isObject(item: any) {
-    return item && typeof item === "object" && !Array.isArray(item);
-}
-
-/**
- * Deep merge two objects.
- */
-export function deepMerge<T>(
-    target: Record<any, any>,
-    ...sources: Record<any, any>[]
-): T {
-    if (!sources.length) return target;
-    const source = sources.shift();
-
-    if (isObject(target) && isObject(source)) {
-        for (const key in source) {
-            if (isObject(source[key])) {
-                if (!target[key]) Object.assign(target, { [key]: {} });
-                deepMerge(target[key], source[key]);
-            } else {
-                Object.assign(target, { [key]: source[key] });
-            }
-        }
-    }
-
-    return deepMerge(target, ...sources) as T;
-}
diff --git a/tsconfig.json b/tsconfig.json
index fef389aa..cd651a3c 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -18,5 +18,6 @@
         "moduleResolution": "NodeNext",
         "skipLibCheck": true
     },
-    "include": ["./src/**/*"]
+    "include": ["./src/**/*"],
+    "files": ["./src/index.d.ts"]
 }


Reviews:
user: login: lowercasename
body: Lovely work, thank you for doing so much boring code! It's definitely an improvement, I've left a few comments. Haven't had a chance to run locally or debug the Cypress issue, but hoping to this weekend.
state: CHANGES_REQUESTED
author_association: OWNER
submitted_at: 2025-04-25T18:20:00Z
user: login: halkeye
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-25T18:38:06Z
user: login: halkeye
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-25T18:40:44Z
user: login: halkeye
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-25T18:41:04Z
user: login: halkeye
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-25T18:41:46Z
user: login: halkeye
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-25T18:42:25Z
user: login: lowercasename
state: COMMENTED
author_association: OWNER
submitted_at: 2025-04-29T19:55:41Z
user: login: lowercasename
state: COMMENTED
author_association: OWNER
submitted_at: 2025-04-29T19:58:33Z
user: login: lowercasename
body: I've tested emails locally and everything seems to be working great so I'm happy to merge this in if you are! 🚀 
state: APPROVED
author_association: OWNER
submitted_at: 2025-04-29T20:08:22Z

Review comments:
diff_hunk: @@ -104,19 +111,21 @@ export const sendEmail = async (
                     html,
                 });
                 return true;
-            } catch (e: any) {
-                if (e.response) {
-                    console.error(e.response.body);
+            } catch (e: unknown | sgHelpers.classes.ResponseError) {
+                if (e instanceof sgHelpers.classes.ResponseError) {
+                    console.error('sendgrid error', e.response.body);
                 } else {
-                    console.error(e);
+                    console.error('sendgrid error', e);
path: src/lib/email.ts
user: login: lowercasename
body: I'm not sure it's worth importing this helpers package just to be able to format the errors properly... does it help with debugging considerably?
created_at: 2025-04-25T18:04:06Z
author_association: OWNER
diff_hunk: @@ -126,22 +135,18 @@ export const sendEmail = async (
                     if (config.nodemailer?.smtp_username) {
                         nodemailerConfig.auth = {
                             user: config.nodemailer?.smtp_username,
-                            pass: config.nodemailer?.smtp_password
+                            pass: config.nodemailer?.smtp_password,
                         };
                     }
 
-                    nodemailerTransporter = nodemailer.createTransport(nodemailerConfig);
+                    nodemailerTransporter =
+                        nodemailer.createTransport(nodemailerConfig);
                 }
                 await nodemailerTransporter.sendMail({
-                    envelope: {
-                        from: config.general.email,
-                        to,
-                        bcc,
-                    },
                     from: config.general.email,
                     to,
                     bcc,
-                    subject,
+                    subject: `${config.general.site_name}: ${subject}`,
path: src/lib/email.ts
user: login: lowercasename
body: If we're using `sendEmailFromTemplate` globally I think it makes more sense to set the subject globally there, and keep this call as pure as possible.
created_at: 2025-04-25T18:05:09Z
author_association: OWNER
diff_hunk: @@ -156,25 +161,42 @@ export const sendEmail = async (
 };
 
 export const sendEmailFromTemplate = async (
-    to: string,
-    bcc: string,
+    to: string | string[],
+    bcc: string | string[] | undefined,
path: src/lib/email.ts
user: login: lowercasename
body: ```suggestion
    bcc?: string | string[],
```
created_at: 2025-04-25T18:05:29Z
author_association: OWNER
diff_hunk: @@ -156,25 +161,42 @@ export const sendEmail = async (
 };
 
 export const sendEmailFromTemplate = async (
-    to: string,
-    bcc: string,
+    to: string | string[],
+    bcc: string | string[] | undefined,
path: src/lib/email.ts
user: login: lowercasename
body: Oh it'll complain about an optional in the middle of a params list. Could you convert this function to take an options param (`sendEmailFromTemplate({ to, bcc, subject ... })`) please? I prefer to do it for functions with more than 3 arguments, and certainly for ones where it makes a big difference if you get the order of params wrong!
created_at: 2025-04-25T18:06:59Z
author_association: OWNER
diff_hunk: @@ -156,25 +161,42 @@ export const sendEmail = async (
 };
 
 export const sendEmailFromTemplate = async (
-    to: string,
-    bcc: string,
+    to: string | string[],
+    bcc: string | string[] | undefined,
     subject: string,
-    template: EmailTemplate,
-    templateData: Record<string, unknown>,
-    req: Request,
+    templateName: EmailTemplateName,
+    templateData: object,
 ): Promise<boolean> => {
-    const html = await renderTemplate(req, `${template}/${template}Html`, {
-        siteName: config.general.site_name,
-        siteLogo: config.general.email_logo_url,
-        domain: config.general.domain,
-        cache: true,
-        layout: "email.handlebars",
-        ...templateData,
-    });
-    const text = await renderTemplate(
-        req,
-        `${template}/${template}Text`,
-        templateData,
-    );
+    const [html, text] = await Promise.all([
+        HandlebarsSingleton.instance.renderView(
+            `./views/emails/${templateName}/${templateName}Html.handlebars`,
+            {
+                domain: config.general.domain,
+                contactEmail: config.general.email,
+                siteName: config.general.site_name,
+                mailService: config.general.mail_service,
+                siteLogo: config.general.email_logo_url,
+                isFederated: config.general.is_federated || true,
+                cache: true,
+                layout: "email.handlebars",
+                ...templateData,
+            }
+        ),
+        HandlebarsSingleton.instance.renderView(
+            `./views/emails/${templateName}/${templateName}Text.handlebars`,
+            {
+                domain: config.general.domain,
+                contactEmail: config.general.email,
+                siteName: config.general.site_name,
+                mailService: config.general.mail_service,
+                siteLogo: config.general.email_logo_url,
+                isFederated: config.general.is_federated || true,
+                cache: true,
+                layout: "email.handlebars",
+                ...templateData,
+            }
+        ),
+    ]);
+
     return await sendEmail(to, bcc, subject, text, html);
path: src/lib/email.ts
user: login: lowercasename
body: Ideally `sendEmail()` should also take an object as a param.
created_at: 2025-04-25T18:08:31Z
author_association: OWNER
diff_hunk: @@ -1,23 +1,55 @@
-import { Request } from "express";
+import hbs, { ExpressHandlebars } from "express-handlebars";
+import { RenderViewOptions } from "express-handlebars/types/index.js";
 
-export const renderTemplate = async (
-    req: Request,
-    templateName: string,
-    data: Record<string, unknown>,
-): Promise<string> => {
-    return new Promise<string>((resolve, reject) => {
-        req.app
-            .get("hbsInstance")
-            .renderView(
-                `./views/emails/${templateName}.handlebars`,
-                data,
-                (err: any, html: string) => {
-                    if (err) {
-                        console.error(err);
-                        reject(err);
-                    }
-                    resolve(html);
+export class HandlebarsSingleton {
path: src/lib/handlebars.ts
user: login: lowercasename
body: I'm not _crazy_ about singletons in what is otherwise a relatively functional (albeit super messy) codebase but I'm happy with it if you think it's the best solution. 
created_at: 2025-04-25T18:09:23Z
author_association: OWNER
diff_hunk: @@ -1,23 +1,55 @@
-import { Request } from "express";
+import hbs, { ExpressHandlebars } from "express-handlebars";
+import { RenderViewOptions } from "express-handlebars/types/index.js";
 
-export const renderTemplate = async (
-    req: Request,
-    templateName: string,
-    data: Record<string, unknown>,
-): Promise<string> => {
-    return new Promise<string>((resolve, reject) => {
-        req.app
-            .get("hbsInstance")
-            .renderView(
-                `./views/emails/${templateName}.handlebars`,
-                data,
-                (err: any, html: string) => {
-                    if (err) {
-                        console.error(err);
-                        reject(err);
-                    }
-                    resolve(html);
+export class HandlebarsSingleton {
+    static #instance: HandlebarsSingleton;
+    hbsInstance: hbs.ExpressHandlebars;
+
+    private constructor() { 
+        this.hbsInstance = hbs.create({
+            defaultLayout: "main",
+            partialsDir: ["views/partials/"],
+            layoutsDir: "views/layouts/",
+            helpers: {
+                plural: function (number: number, text: string) {
+                    const singular = number === 1;
+                    // If no text parameter was given, just return a conditional s.
+                    if (typeof text !== "string") return singular ? "" : "s";
+                    // Split with regex into group1/group2 or group1(group3)
+                    const match = text.match(/^([^()\/]+)(?:\/(.+))?(?:\((\w+)\))?/);
+                    // If no match, just append a conditional s.
+                    if (!match) return text + (singular ? "" : "s");
+                    // We have a good match, so fire away
+                    return (
+                        (singular && match[1]) || // Singular case
+                        match[2] || // Plural case: 'bagel/bagels' --> bagels
+                        match[1] + (match[3] || "s")
+                    ); // Plural case: 'bagel(s)' or 'bagel' --> bagels
+                },
+                json: function (context: object) {
+                    return JSON.stringify(context);
                 },
-            );
-    });
-};
+            },
+        });
+    }
+
+    public static get instance(): HandlebarsSingleton {
+        if (!HandlebarsSingleton.#instance) {
+            HandlebarsSingleton.#instance = new HandlebarsSingleton();
+        }
+
+        return HandlebarsSingleton.#instance;
+    }
+    
+    public get engine(): ExpressHandlebars["engine"] {
+        return this.hbsInstance.engine;
+    }
+
+    /**
+     * Finally, any singleton can define some business logic, which can be
+     * executed on its instance.
+     */
path: src/lib/handlebars.ts
user: login: lowercasename
body: Unnecessary comment!
created_at: 2025-04-25T18:10:04Z
author_association: OWNER
diff_hunk: @@ -44,9 +38,7 @@ const nanoid = customAlphabet(
 const router = express.Router();
 
 let sendEmails = false;
-initEmailService().then((emailService) => {
-    sendEmails = emailService
-});
+initEmailService().then((emailService) => (sendEmails = emailService));
path: src/routes.js
user: login: lowercasename
body: I'm aware this is from the previous PR but I wonder why we need this `sendEmails` global flag here at all. Can `sendEmailFromTemplate` not make this check for us? We could move the flag and the initializer to `lib/email`.
created_at: 2025-04-25T18:13:24Z
author_association: OWNER
diff_hunk: @@ -316,63 +311,29 @@ router.post("/deleteevent/:eventID/:editToken", (req, res) => {
 
                                 // Send emails here otherwise they don't exist lol
                                 if (sendEmails) {
-                                    const attendeeEmails = event.attendees
-                                        .filter(
+                                    const attendeeEmails = event?.attendees?.filter(
                                             (o) =>
                                                 o.status === "attending" &&
                                                 o.email,
                                         )
-                                        .map((o) => o.email);
+                                        .map((o) => o.email || '') || [];
                                     if (attendeeEmails.length) {
                                         console.log(
                                             "Sending emails to: " +
-                                            attendeeEmails,
+                                                attendeeEmails,
                                         );
-                                        req.app.get("hbsInstance").renderView(
-                                            "./views/emails/deleteEvent/deleteEventHtml.handlebars",
+                                        sendEmailFromTemplate(
+                                            attendeeEmails, 
+                                            '',
+                                            `${event?.name} was deleted`,
+                                            "deleteEvent",
                                             {
-                                                siteName,
-                                                siteLogo,
-                                                domain,
-                                                eventName: event.name,
-                                                cache: true,
-                                                layout: "email.handlebars",
-                                            },
-                                            function (err, html) {
-                                                const msg = {
-                                                    to: attendeeEmails,
-                                                    from: contactEmail,
-                                                    subject: `${siteName}: ${event.name} was deleted`,
-                                                    html,
-                                                };
-                                                switch (mailService) {
-                                                    case "sendgrid":
-                                                        sgMail
-                                                            .sendMultiple(msg)
-                                                            .catch((e) => {
-                                                                console.error(
-                                                                    e.toString(),
-                                                                );
-                                                                res.status(
-                                                                    500,
-                                                                ).end();
-                                                            });
-                                                        break;
-                                                    case "nodemailer":
-                                                        nodemailerTransporter
-                                                            .sendMail(msg)
-                                                            .catch((e) => {
-                                                                console.error(
-                                                                    e.toString(),
-                                                                );
-                                                                res.status(
-                                                                    500,
-                                                                ).end();
-                                                            });
-                                                        break;
-                                                }
+                                                eventName: event?.name,
                                             },
-                                        );
+                                        ).catch((e) => {
+                                            console.error('error sending attendy email', e.toString());
path: src/routes.js
user: login: lowercasename
body: ```suggestion
                                            console.error('error sending attendee email', e.toString());
```
created_at: 2025-04-25T18:14:07Z
author_association: OWNER
diff_hunk: @@ -659,55 +620,40 @@ router.post("/attendevent/:eventID", async (req, res) => {
                 "attendees.$.name": req.body.attendeeName,
                 "attendees.$.email": req.body.attendeeEmail,
                 "attendees.$.number": req.body.attendeeNumber,
-                "attendees.$.visibility": !!req.body.attendeeVisible ? "public" : "private",
+                "attendees.$.visibility": req.body.attendeeVisible
+                    ? "public"
+                    : "private",
path: src/routes.js
user: login: lowercasename
body: Your removal of the `!!` implies you have a lot more faith in the data integrity of MongoDB fields than I do. :P
created_at: 2025-04-25T18:15:12Z
author_association: OWNER
diff_hunk: @@ -104,19 +111,21 @@ export const sendEmail = async (
                     html,
                 });
                 return true;
-            } catch (e: any) {
-                if (e.response) {
-                    console.error(e.response.body);
+            } catch (e: unknown | sgHelpers.classes.ResponseError) {
+                if (e instanceof sgHelpers.classes.ResponseError) {
+                    console.error('sendgrid error', e.response.body);
                 } else {
-                    console.error(e);
+                    console.error('sendgrid error', e);
path: src/lib/email.ts
user: login: halkeye
body: not at all, it was a drive by typescript fix. It didn't like me leaving it unknown or Error (I'm a go developer at work, so my typescript keeps getting rusty)
created_at: 2025-04-25T18:38:06Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1,23 +1,55 @@
-import { Request } from "express";
+import hbs, { ExpressHandlebars } from "express-handlebars";
+import { RenderViewOptions } from "express-handlebars/types/index.js";
 
-export const renderTemplate = async (
-    req: Request,
-    templateName: string,
-    data: Record<string, unknown>,
-): Promise<string> => {
-    return new Promise<string>((resolve, reject) => {
-        req.app
-            .get("hbsInstance")
-            .renderView(
-                `./views/emails/${templateName}.handlebars`,
-                data,
-                (err: any, html: string) => {
-                    if (err) {
-                        console.error(err);
-                        reject(err);
-                    }
-                    resolve(html);
+export class HandlebarsSingleton {
path: src/lib/handlebars.ts
user: login: halkeye
body: I was trying to avoid duplication of having hbs created multiple places (cause it has a cache) or passed into every function

I liked this pattern for this because you can eventually make more helper functions. Handlebars.instance.renderEmail() Handlebars.instance.renderView() but as I learned more about the codebase, I see it wasn't really needed.

If anything I'm thinking maybe an email class, and app.set() that, and have handlebars passed into that? I think thats nicer
created_at: 2025-04-25T18:40:44Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1,23 +1,55 @@
-import { Request } from "express";
+import hbs, { ExpressHandlebars } from "express-handlebars";
+import { RenderViewOptions } from "express-handlebars/types/index.js";
 
-export const renderTemplate = async (
-    req: Request,
-    templateName: string,
-    data: Record<string, unknown>,
-): Promise<string> => {
-    return new Promise<string>((resolve, reject) => {
-        req.app
-            .get("hbsInstance")
-            .renderView(
-                `./views/emails/${templateName}.handlebars`,
-                data,
-                (err: any, html: string) => {
-                    if (err) {
-                        console.error(err);
-                        reject(err);
-                    }
-                    resolve(html);
+export class HandlebarsSingleton {
+    static #instance: HandlebarsSingleton;
+    hbsInstance: hbs.ExpressHandlebars;
+
+    private constructor() { 
+        this.hbsInstance = hbs.create({
+            defaultLayout: "main",
+            partialsDir: ["views/partials/"],
+            layoutsDir: "views/layouts/",
+            helpers: {
+                plural: function (number: number, text: string) {
+                    const singular = number === 1;
+                    // If no text parameter was given, just return a conditional s.
+                    if (typeof text !== "string") return singular ? "" : "s";
+                    // Split with regex into group1/group2 or group1(group3)
+                    const match = text.match(/^([^()\/]+)(?:\/(.+))?(?:\((\w+)\))?/);
+                    // If no match, just append a conditional s.
+                    if (!match) return text + (singular ? "" : "s");
+                    // We have a good match, so fire away
+                    return (
+                        (singular && match[1]) || // Singular case
+                        match[2] || // Plural case: 'bagel/bagels' --> bagels
+                        match[1] + (match[3] || "s")
+                    ); // Plural case: 'bagel(s)' or 'bagel' --> bagels
+                },
+                json: function (context: object) {
+                    return JSON.stringify(context);
                 },
-            );
-    });
-};
+            },
+        });
+    }
+
+    public static get instance(): HandlebarsSingleton {
+        if (!HandlebarsSingleton.#instance) {
+            HandlebarsSingleton.#instance = new HandlebarsSingleton();
+        }
+
+        return HandlebarsSingleton.#instance;
+    }
+    
+    public get engine(): ExpressHandlebars["engine"] {
+        return this.hbsInstance.engine;
+    }
+
+    /**
+     * Finally, any singleton can define some business logic, which can be
+     * executed on its instance.
+     */
path: src/lib/handlebars.ts
user: login: halkeye
body: hahaha yes. I just copy and pasted a typescript singleton template my bad.
created_at: 2025-04-25T18:41:04Z
author_association: CONTRIBUTOR
diff_hunk: @@ -44,9 +38,7 @@ const nanoid = customAlphabet(
 const router = express.Router();
 
 let sendEmails = false;
-initEmailService().then((emailService) => {
-    sendEmails = emailService
-});
+initEmailService().then((emailService) => (sendEmails = emailService));
path: src/routes.js
user: login: halkeye
body: yesssssssssssss
I didn't know what it did either, but reading it through now sendEmail was to prevent calls to sendgrid/nodemailer, so better in email
created_at: 2025-04-25T18:41:46Z
author_association: CONTRIBUTOR
diff_hunk: @@ -659,55 +620,40 @@ router.post("/attendevent/:eventID", async (req, res) => {
                 "attendees.$.name": req.body.attendeeName,
                 "attendees.$.email": req.body.attendeeEmail,
                 "attendees.$.number": req.body.attendeeNumber,
-                "attendees.$.visibility": !!req.body.attendeeVisible ? "public" : "private",
+                "attendees.$.visibility": req.body.attendeeVisible
+                    ? "public"
+                    : "private",
path: src/routes.js
user: login: halkeye
body: eslint did it :) it'll still work the same way though, javascript will treat it as a truthy value and return either string.
created_at: 2025-04-25T18:42:25Z
author_association: CONTRIBUTOR
diff_hunk: @@ -1,14 +1,17 @@
 import "express";
-import { GathioConfig } from "./lib/config.js";
+import { GathioConfig } from "./lib/config.ts";
+import { EmailService } from "./lib/email.ts";
+import { ExpressHandlebars } from "express-handlebars";
 
 interface Locals {
     config: GathioConfig;
 }
 
-declare module "express" {
-    export interface Response {
-        locals: {
-            config?: GathioConfig;
-        };
+declare global {
+    namespace Express {
+        interface Request extends Express.Request {
+            hbsInstance: ExpressHandlebars;
+            emailService: EmailService;
+        }
     }
-}
+}
path: src/index.d.ts
user: login: lowercasename
body: Nice one 🙏 
created_at: 2025-04-29T19:55:41Z
author_association: OWNER
diff_hunk: @@ -104,19 +111,21 @@ export const sendEmail = async (
                     html,
                 });
                 return true;
-            } catch (e: any) {
-                if (e.response) {
-                    console.error(e.response.body);
+            } catch (e: unknown | sgHelpers.classes.ResponseError) {
+                if (e instanceof sgHelpers.classes.ResponseError) {
+                    console.error('sendgrid error', e.response.body);
                 } else {
-                    console.error(e);
+                    console.error('sendgrid error', e);
path: src/lib/email.ts
user: login: lowercasename
body: I just tend to leave them `unknown` but this is absolutely fine and indeed better!
created_at: 2025-04-29T19:58:33Z
author_association: OWNER

PR comments:
user: login: halkeye
created_at: 2025-04-23T22:09:48Z
body: I'm sorry all the formatting changed. I've been working on getting eslint running again with typescript, so my editor may have re-written some stuff.

I'll get a PR up soon with eslint working so a) consistent formatting, and b) no more undefined values errors :)
author_association: CONTRIBUTOR
user: login: halkeye
created_at: 2025-04-23T22:31:05Z
body: rawr, i didn't notice sendEmailFromTemplate already exists. I'll try to do some refactoring again after work
author_association: CONTRIBUTOR
user: login: halkeye
created_at: 2025-04-24T00:30:50Z
body: commit 206dade91f320566a71fe758e118766a34508c01 (HEAD -> fix-nodemailer, origin/fix-nodemailer)
Author: Gavin Mogan <git@gavinmogan.com>
Date:   Wed Apr 23 17:27:55 2025 -0700

    Refactor for everywhere to use sendEmailFromTemplate everywhere

    * Created a singleton to house handlebars so req doesn't need to be
      passed everywhere (should make unit testing easier later)
    * Subjectline for sendgrid and nodemailer are both always prefixed in
      sendEmail()
    * removed prefix subjectline from all other email places
    * added a couple if (!event) { return 404 } to help make typescript
      happy
    * some minor eslint auto fixes (looks like let => const where it can)
author_association: CONTRIBUTOR
user: login: halkeye
created_at: 2025-04-24T04:14:57Z
body: @lowercasename for the life of me I can't figure out why cypress is failing
it fails every time locally with firefox
it doesn't fail with chrome
from what i can tell, cy.visit("/new") isn't actually going to new
i can't see anything i changed that would have caused it
author_association: CONTRIBUTOR
user: login: halkeye
created_at: 2025-04-25T18:42:55Z
body: super good comments now that I had a couple days to think about it. I was rushing cause i wanted to setup an event. I'll try to get it updated tonight/tomorrow
author_association: CONTRIBUTOR
user: login: lowercasename
created_at: 2025-04-25T19:57:05Z
body: I was actually gonna suggest making the emailer class a singleton or at least attaching it to the existing singleton class, so feel very welcome to do that if you have the energy!

I wish Gathio was written in Go 😭 
author_association: OWNER
user: login: halkeye
created_at: 2025-04-26T04:48:40Z
body: Okay, refactored again :)

I know i want to run eslint --fix, and upgrade express (so route functions can return promises), and finish cleaning up typescript so 🤞🤞🤞🤞


> I wish Gathio was written in Go 😭

one thing at a time :)
author_association: CONTRIBUTOR
user: login: halkeye
created_at: 2025-04-26T04:58:54Z
body: another two cypress tests failing. I tried it out by hand (as i am having trouble running cypress in wsl) and certainly can see public groups being created.
author_association: CONTRIBUTOR
user: login: lowercasename
created_at: 2025-04-28T10:47:26Z
body: I've worked out what's happening with the tests.

1. These lines:
```
    if (_resolvedConfig) {
        return _resolvedConfig;
    }
```
...mean that the config is only instantiated once. However, the Cypress tests rely on the config being updated using a cookie (`getConfigMiddleware()`).
2. The tests run in order. The `publicEvent.cy.ts` test sets the config to require creator email addresses.
3. The next test, `publicEvent.cy.ts`, navigates to `/new`. But this page no longer contains the new event form, it contains the message that event creation is restricted.
4. Same happens with `publicGroup.cy.ts`.

You can replicate this by running the public event test locally, then running any other test. The others should all fail.

Maybe the config doesn't need to be instantiated just once? Or a workaround needs to be created for Cypress.
author_association: OWNER
user: login: halkeye
created_at: 2025-04-28T15:38:26Z
body: Okay i'll poke tonight. I turned config into singleton cause it was spitting out the warning about no email service multiple times a request
author_association: CONTRIBUTOR
user: login: halkeye
created_at: 2025-04-28T17:34:56Z
body: ps, my vote is get it working as quickly as possible and coming back with a refactor later
so i am leaning towards just un-singletoning the config
author_association: CONTRIBUTOR
user: login: halkeye
created_at: 2025-04-29T02:17:05Z
body: ohhhhhh
your deep merge is custom and actually mutates.
i'm gonna try https://www.npmjs.com/package/ts-deepmerge since its typescript and doesn't mutate
author_association: CONTRIBUTOR
user: login: halkeye
created_at: 2025-04-29T20:38:23Z
body: I'm happy. As far as I could test everything worked
author_association: CONTRIBUTOR