summaryrefslogtreecommitdiff
path: root/src/lib/email.ts
diff options
context:
space:
mode:
authorRaphael Kabo <mail@raphaelkabo.com>2025-05-28 18:32:47 +0100
committerRaphael Kabo <mail@raphaelkabo.com>2025-05-28 18:32:47 +0100
commita6f8ec770d06ce33042ed3f222cba786897e0233 (patch)
treea060e72668de41fcbeae5e891ee86b096b096f26 /src/lib/email.ts
parent08fa2f616c90e59066d0308097c65c424b5b4a88 (diff)
parentfd637b405c8784a07dabd54b10fda98ad9f4a4ad (diff)
Merge remote-tracking branch 'origin/main' into clearer-editing-mode
Diffstat (limited to 'src/lib/email.ts')
-rw-r--r--src/lib/email.ts292
1 files changed, 181 insertions, 111 deletions
diff --git a/src/lib/email.ts b/src/lib/email.ts
index 7b7a7a1..fc585a1 100644
--- a/src/lib/email.ts
+++ b/src/lib/email.ts
@@ -1,13 +1,16 @@
-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";
+import Mailgun from "mailgun.js";
+import { IMailgunClient } from "node_modules/mailgun.js/Types/Interfaces/index.js";
+
const config = getConfig();
-type EmailTemplate =
+type EmailTemplateName =
| "addEventAttendee"
| "addEventComment"
| "createEvent"
@@ -16,58 +19,90 @@ 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.",
- );
+export class EmailService {
+ nodemailerTransporter: Transporter | undefined = undefined;
+ sgMail: typeof sgMail | undefined = undefined;
+ mailgunClient: IMailgunClient | 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(
+ "Sendgrid is configured as the email service, but no API key is provided. Please provide an API key in the config file.",
+ );
+ }
+ this.sgMail = sgMail;
+ this.sgMail.setApiKey(config.sendgrid.api_key);
+ console.log("Sendgrid is ready to send emails.");
+ break;
}
- 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 {
+ case "mailgun": {
if (
- !config.nodemailer?.smtp_server ||
- !config.nodemailer?.smtp_port
+ !config.mailgun?.api_key ||
+ !config.mailgun?.api_url ||
+ !config.mailgun?.domain
) {
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.",
+ "Mailgun 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;
+ const mailgun = new Mailgun(FormData);
+ this.mailgunClient = mailgun.client({
+ username: "api",
+ key: config.mailgun.api_key,
+ url: config.mailgun.api_url,
+ });
+ // TODO: Can we verify the Mailgun connection?
+ console.log("Mailgun 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 +111,72 @@ 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.mailgunClient) {
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);
+ if (!config.mailgun?.domain) {
+ return exitWithError(
+ "Mailgun is configured as the email service, but no domain is provided. Please provide a domain in the config file.",
+ );
}
- await nodemailerTransporter.sendMail({
- envelope: {
+ await this.mailgunClient.messages.create(
+ config.mailgun.domain,
+ {
from: config.general.email,
to,
bcc,
+ subject: `${config.general.site_name}: ${subject}`,
+ text,
+ html,
},
+ );
+ return true;
+ } catch (e: any) {
+ if (e.response) {
+ console.error(e.response.body);
+ } else {
+ console.error(e);
+ }
+ return false;
+ }
+ } else if (this.nodemailerTransporter) {
+ try {
+ await this.nodemailerTransporter.sendMail({
from: config.general.email,
to,
bcc,
@@ -150,31 +189,62 @@ 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,
+ });
+ }
+}