Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
♻️ Email package: per-template send functions + branding as props (RAL-1218) (#2416)
Luke Vella7882c8b5e78a
diff --git a/apps/web/src/app/api/stripe/webhook/handlers/checkout/completed.ts b/apps/web/src/app/api/stripe/webhook/handlers/checkout/completed.tsindex a2114f242..32ecd1866 100644--- a/apps/web/src/app/api/stripe/webhook/handlers/checkout/completed.ts+++ b/apps/web/src/app/api/stripe/webhook/handlers/checkout/completed.ts@@ -1,9 +1,10 @@import type { Stripe } from "@rallly/billing";+import { sendLicenseKeyEmail } from "@rallly/emails/templates/license-key";+import { getInstanceBranding } from "@/emails/branding";import { env } from "@/env";import { posthog } from "@/features/analytics/posthog";import { licenseCheckoutMetadataSchema } from "@/features/licensing/schema";import { licenseManager } from "@/features/licensing/server";-import { getEmailClient } from "@/utils/emails";export async function onCheckoutSessionCompleted(event: Stripe.Event) {const checkoutSession = event.data.object as Stripe.Checkout.Session;@@ -51,14 +52,10 @@ export async function onCheckoutSessionCompleted(event: Stripe.Event) {);}- const emailClient = await getEmailClient();-- await emailClient.sendTemplate("LicenseKeyEmail", {+ await sendLicenseKeyEmail({to: email,- from: {- name: "Luke from Rallly",- address: env.SUPPORT_EMAIL,- },+ from: { name: "Luke from Rallly", address: env.SUPPORT_EMAIL },+ branding: await getInstanceBranding(),props: {licenseKey: license.data.key,seats,diff --git a/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/created.ts b/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/created.tsindex e4748e402..dbe643771 100644--- a/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/created.ts+++ b/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/created.ts@@ -1,10 +1,10 @@import type { Stripe } from "@rallly/billing";import { prisma } from "@rallly/database";+import { sendRawEmail } from "@rallly/emails";import { after } from "next/server";import { env } from "@/env";import { posthog } from "@/features/analytics/posthog";import { subscriptionMetadataSchema } from "@/features/subscription/schema";-import { getEmailClient } from "@/utils/emails";import {getExpandedSubscription,getSubscriptionDetails,@@ -124,13 +124,9 @@ export async function onCustomerSubscriptionCreated(event: Stripe.Event) {});if (user) {- const emailClient = await getEmailClient();- await emailClient.sendEmail({+ await sendRawEmail({to: user.email,- from: {- name: "Luke from Rallly",- address: env.SUPPORT_EMAIL,- },+ from: { name: "Luke from Rallly", address: env.SUPPORT_EMAIL },subject: "Thanks for subscribing to Rallly Pro",text: ["Hey there,",diff --git a/apps/web/src/emails/branding.ts b/apps/web/src/emails/branding.tsnew file mode 100644index 000000000..859e3ee58--- /dev/null+++ b/apps/web/src/emails/branding.ts@@ -0,0 +1,38 @@+import type { EmailBranding } from "@rallly/emails";++import { getInstanceBrandingConfig } from "@/features/branding/queries";+import { resolveStorageUrl } from "@/utils/storage";++/**+ * Branding for emails that represent the instance/product (auth, billing,+ * account, moderation, etc.).+ */+export async function getInstanceBranding(): Promise<EmailBranding> {+ const branding = await getInstanceBrandingConfig();+ return {+ primaryColor: branding.primaryColor.light,+ logoUrl: branding.logoIcon,+ appName: branding.appName,+ hideAttribution: branding.hideAttribution,+ };+}++/**+ * Branding for emails sent on behalf of a space — instance branding with the+ * space's logo/color applied when the space has custom branding enabled.+ */+export async function getSpaceBranding(space: {+ showBranding: boolean;+ primaryColor: string | null;+ image: string | null;+}): Promise<EmailBranding> {+ const instance = await getInstanceBranding();+ if (!space.showBranding) {+ return instance;+ }+ return {+ ...instance,+ primaryColor: space.primaryColor ?? instance.primaryColor,+ logoUrl: space.image ? resolveStorageUrl(space.image) : instance.logoUrl,+ };+}diff --git a/apps/web/src/features/moderation/index.ts b/apps/web/src/features/moderation/index.tsindex 624421e6f..b2452fb58 100644--- a/apps/web/src/features/moderation/index.ts+++ b/apps/web/src/features/moderation/index.ts@@ -1,8 +1,8 @@import { prisma } from "@rallly/database";+import { sendRawEmail } from "@rallly/emails";import { createLogger } from "@rallly/logger";import { after } from "next/server";import { env } from "@/env";-import { getEmailClient } from "@/utils/emails";import type { ModerationResult, ModerationVerdict } from "./libs/ai-moderation";import { moderateContentWithAI } from "./libs/ai-moderation";import { containsSuspiciousPatterns } from "./libs/pattern-moderation";@@ -100,9 +100,8 @@ export async function moderateContent({{ userId, verdict: result.verdict, reason: result.reason },`Content ${result.verdict} by AI moderation`,);- const emailClient = await getEmailClient();after(() =>- emailClient.sendEmail({+ sendRawEmail({to: env.SUPPORT_EMAIL,subject: `Content ${result.verdict} by moderation`,text: [diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.tsindex 98a51f0b8..c9f798898 100644--- a/apps/web/src/lib/auth.ts+++ b/apps/web/src/lib/auth.ts@@ -1,4 +1,6 @@import { prisma } from "@rallly/database";+import { sendRegisterEmail } from "@rallly/emails/templates/register";+import { sendResetPasswordEmail } from "@rallly/emails/templates/reset-password";import { createLogger } from "@rallly/logger";import { absoluteUrl } from "@rallly/utils/absolute-url";import type { BetterAuthPlugin } from "better-auth";@@ -21,13 +23,13 @@ import { isEmailBlocked } from "@/auth/helpers/is-email-blocked";import { linkAnonymousUser } from "@/auth/helpers/merge-user";import { isTemporaryEmail } from "@/auth/helpers/temp-email-domains";import { hostOnlyCookieCleanup } from "@/auth/plugins/host-only-cookie-cleanup";+import { getInstanceBranding } from "@/emails/branding";import { env } from "@/env";import { posthog } from "@/features/analytics/posthog";import { createSpace } from "@/features/space/mutations";import { getTranslation } from "@/i18n/server";import { getLocale } from "@/i18n/server/get-locale";import { redis } from "@/lib/kv";-import { getEmailClient } from "@/utils/emails";import { getValueByPath } from "@/utils/get-value-by-path";const kv = redis;@@ -108,15 +110,12 @@ export const authLib = betterAuth({const locale ="locale" in user ? (user.locale as string) : await getLocale();- await (await getEmailClient({ locale })).sendTemplate(- "ResetPasswordEmail",- {- to: user.email,- props: {- resetLink: url,- },- },- );+ await sendResetPasswordEmail({+ to: user.email,+ locale,+ branding: await getInstanceBranding(),+ props: { resetLink: url },+ });},onPasswordReset: async ({ user }) => {posthog()?.capture({@@ -153,24 +152,17 @@ export const authLib = betterAuth({overrideDefaultEmailVerification: true,async sendVerificationOTP({ email, otp, type }) {const locale = await getLocale(); // TODO: Get locale from email- const emailClient = await getEmailClient({ locale });+ const branding = await getInstanceBranding();switch (type) {// We're not actually using the sign-in type anymore since we just we have `autoSignInAfterVerification` enabled.// This lets us keep things a bit simpler since we share the same verification flow for both login and registration.case "sign-in":- after(() =>- emailClient.sendTemplate("RegisterEmail", {- to: email,- props: {- code: otp,- },- }),- );- break;case "email-verification":after(() =>- emailClient.sendTemplate("RegisterEmail", {+ sendRegisterEmail({to: email,+ locale,+ branding,props: { code: otp },}),);diff --git a/apps/web/src/trpc/routers/events.ts b/apps/web/src/trpc/routers/events.tsindex b15a1fd0f..1588166cd 100644--- a/apps/web/src/trpc/routers/events.ts+++ b/apps/web/src/trpc/routers/events.ts@@ -1,8 +1,10 @@import { subject } from "@casl/ability";import { prisma } from "@rallly/database";+import { sendEventCanceledEmail } from "@rallly/emails/templates/event-canceled";import { TRPCError } from "@trpc/server";import { after } from "next/server";import * as z from "zod";+import { getInstanceBranding } from "@/emails/branding";import { parseConferencing } from "@/features/conferencing/data";import { getConferencingUri } from "@/features/conferencing/utils";import { parseLocation } from "@/features/location/data";@@ -10,7 +12,6 @@ import { formatLocationText } from "@/features/location/utils";import { getEventsChronological } from "@/features/scheduled-event/data";import { formatEventDateTime } from "@/features/scheduled-event/utils";import { defineAbilityForMember } from "@/features/space/member/ability";-import { getEmailClient } from "@/utils/emails";import { createIcsEvent } from "@/utils/ics";import { router, spaceProcedure } from "../trpc";@@ -170,10 +171,15 @@ export const events = router({inviteeTimeZone: invite.inviteeTimeZone,});- const emailClient = await getEmailClient();- after(() =>- emailClient.sendTemplate("EventCanceledEmail", {+ after(async () =>+ sendEventCanceledEmail({to: invite.inviteeEmail,+ branding: await getInstanceBranding(),+ icalEvent: {+ filename: "cancel.ics",+ method: "cancel",+ content: cancelEvent.value,+ },props: {title: updatedEvent.title,hostName: ctx.user.name,@@ -182,11 +188,6 @@ export const events = router({date,time,},- icalEvent: {- filename: "cancel.ics",- method: "cancel",- content: cancelEvent.value,- },}),);}diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.tsindex 027d7a899..b63141fa2 100644--- a/apps/web/src/trpc/routers/polls.ts+++ b/apps/web/src/trpc/routers/polls.ts@@ -1,11 +1,15 @@import { getPolls } from "@rallly/api-core/polls/data";import type { PollStatus } from "@rallly/database";import { prisma } from "@rallly/database";+import { sendFinalizeHostEmail } from "@rallly/emails/templates/finalized-host";+import { sendFinalizeParticipantEmail } from "@rallly/emails/templates/finalized-participant";+import { sendNewPollEmail } from "@rallly/emails/templates/new-poll";import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";import { nanoid } from "@rallly/utils/nanoid";import { TRPCError } from "@trpc/server";import { after } from "next/server";import * as z from "zod";+import { getInstanceBranding, getSpaceBranding } from "@/emails/branding";import { posthog } from "@/features/analytics/posthog";import { moderateContent } from "@/features/moderation";import { canUserManagePoll } from "@/features/poll/helpers";@@ -13,9 +17,7 @@ import { hasPollAdminAccess } from "@/features/poll/query";import { formatEventDateTime } from "@/features/scheduled-event/utils";import { getActiveSpaceForUser } from "@/features/space/data";import { dayjs } from "@/lib/dayjs";-import { getEmailClient } from "@/utils/emails";import { createIcsEvent } from "@/utils/ics";-import { resolveStorageUrl } from "@/utils/storage";import {createRateLimitMiddleware,possiblyPublicProcedure,@@ -219,12 +221,11 @@ export const polls = router({});if (user) {- const emailClient = await getEmailClient({- locale: ctx.user.locale ?? undefined,- });- after(() =>- emailClient.sendTemplate("NewPollEmail", {+ after(async () =>+ sendNewPollEmail({to: user.email,+ locale: ctx.user.locale ?? undefined,+ branding: await getInstanceBranding(),props: {title: poll.title,name: user.name,@@ -944,19 +945,18 @@ export const polls = router({const hostEmail = poll.user.email;const hostName = poll.user.name;+ const hostLocale = poll.user.locale ?? undefined;const space = poll.space;- const participantBrandingOptions = space?.showBranding- ? {- primaryColor: space.primaryColor ?? undefined,- logoUrl: space.image ? resolveStorageUrl(space.image) : undefined,- }- : {};- const emailClient = await getEmailClient({- locale: poll.user.locale ?? undefined,- });- after(() =>- emailClient.sendTemplate("FinalizeHostEmail", {+ after(async () =>+ sendFinalizeHostEmail({to: hostEmail,+ locale: hostLocale,+ branding: await getInstanceBranding(),+ icalEvent: {+ filename: "invite.ics",+ method: "request",+ content: event.value,+ },props: {name: hostName,pollUrl: absoluteUrl(`/poll/${poll.id}`),@@ -974,11 +974,6 @@ export const polls = router({dow,time,},- icalEvent: {- filename: "invite.ics",- method: "request",- content: event.value,- },}),);@@ -990,13 +985,18 @@ export const polls = router({timeZone: scheduledEvent.timeZone,inviteeTimeZone: p.timeZone,});- const emailClient = await getEmailClient({- locale: p.locale ?? undefined,- ...participantBrandingOptions,- });- after(() =>- emailClient.sendTemplate("FinalizeParticipantEmail", {+ after(async () =>+ sendFinalizeParticipantEmail({to: p.email,+ locale: p.locale ?? undefined,+ branding: space+ ? await getSpaceBranding(space)+ : await getInstanceBranding(),+ icalEvent: {+ filename: "invite.ics",+ method: "request",+ content: event.value,+ },props: {pollUrl: absoluteUrl(`/invite/${poll.id}`),title: poll.title,@@ -1006,11 +1006,6 @@ export const polls = router({dow,time,},- icalEvent: {- filename: "invite.ics",- method: "request",- content: event.value,- },}),);}diff --git a/apps/web/src/trpc/routers/polls/comments.ts b/apps/web/src/trpc/routers/polls/comments.tsindex a8471d7aa..dc6c7a582 100644--- a/apps/web/src/trpc/routers/polls/comments.ts+++ b/apps/web/src/trpc/routers/polls/comments.ts@@ -1,13 +1,14 @@import { prisma } from "@rallly/database";+import { sendNewCommentEmail } from "@rallly/emails/templates/new-comment";import { createLogger } from "@rallly/logger";import { absoluteUrl } from "@rallly/utils/absolute-url";import { TRPCError } from "@trpc/server";import { after } from "next/server";import * as z from "zod";+import { getInstanceBranding } from "@/emails/branding";import { posthog } from "@/features/analytics/posthog";import { getNotificationRecipient } from "@/features/notifications/queries";import { hasPollAdminAccess } from "@/features/poll/query";-import { getEmailClient } from "@/utils/emails";import {createRateLimitMiddleware,publicProcedure,@@ -137,12 +138,11 @@ export const comments = router({});if (recipient) {- const emailClient = await getEmailClient({- locale: recipient.locale ?? undefined,- });- after(() =>- emailClient.sendTemplate("NewCommentEmail", {+ after(async () =>+ sendNewCommentEmail({to: recipient.email,+ locale: recipient.locale ?? undefined,+ branding: await getInstanceBranding(),props: {authorName,pollUrl: absoluteUrl(`/poll/${poll.id}`),diff --git a/apps/web/src/trpc/routers/polls/participants.ts b/apps/web/src/trpc/routers/polls/participants.tsindex b145b4e10..cca2cb1db 100644--- a/apps/web/src/trpc/routers/polls/participants.ts+++ b/apps/web/src/trpc/routers/polls/participants.ts@@ -1,15 +1,16 @@import type { Participant, VoteType } from "@rallly/database";import { prisma } from "@rallly/database";+import { sendNewParticipantEmail } from "@rallly/emails/templates/new-participant";+import { sendNewParticipantConfirmationEmail } from "@rallly/emails/templates/new-participant-confirmation";import { createLogger } from "@rallly/logger";import { absoluteUrl } from "@rallly/utils/absolute-url";import { TRPCError } from "@trpc/server";import { after } from "next/server";import * as z from "zod";+import { getInstanceBranding, getSpaceBranding } from "@/emails/branding";import { posthog } from "@/features/analytics/posthog";import { getNotificationRecipient } from "@/features/notifications/queries";import { hasPollAdminAccess } from "@/features/poll/query";-import { getEmailClient } from "@/utils/emails";-import { resolveStorageUrl } from "@/utils/storage";import {createRateLimitMiddleware,publicProcedure,@@ -86,11 +87,10 @@ async function sendNewResponseNotificationEmail({return;}- const emailClient = await getEmailClient({- locale: recipient.locale ?? undefined,- });- await emailClient.sendTemplate("NewParticipantEmail", {+ await sendNewParticipantEmail({to: recipient.email,+ locale: recipient.locale ?? undefined,+ branding: await getInstanceBranding(),props: {participantName,pollUrl: absoluteUrl(`/poll/${pollId}`),@@ -316,21 +316,14 @@ export const participants = router({const token = await createParticipantEditToken(ctx.user.id);const space = participant.poll.space;- const emailClient = await getEmailClient({- locale: ctx.locale,- ...(space?.showBranding- ? {- primaryColor: space.primaryColor ?? undefined,- logoUrl: space.image- ? resolveStorageUrl(space.image)- : undefined,- }- : {}),- });- after(() =>- emailClient.sendTemplate("NewParticipantConfirmationEmail", {+ after(async () =>+ sendNewParticipantConfirmationEmail({to: email,+ locale: ctx.locale,+ branding: space+ ? await getSpaceBranding(space)+ : await getInstanceBranding(),props: {title: participant.poll.title,editSubmissionUrl: absoluteUrl(diff --git a/apps/web/src/trpc/routers/spaces.ts b/apps/web/src/trpc/routers/spaces.tsindex ee844d3c5..62e8b676d 100644--- a/apps/web/src/trpc/routers/spaces.ts+++ b/apps/web/src/trpc/routers/spaces.ts@@ -1,10 +1,12 @@import { subject } from "@casl/ability";import { prisma } from "@rallly/database";+import { sendSpaceInviteEmail } from "@rallly/emails/templates/space-invite";import { createLogger } from "@rallly/logger";import { absoluteUrl } from "@rallly/utils/absolute-url";import { TRPCError } from "@trpc/server";import { after } from "next/server";import * as z from "zod";+import { getInstanceBranding } from "@/emails/branding";import { posthog } from "@/features/analytics/posthog";import { defineAbilityForSpace } from "@/features/space/ability";import {@@ -27,7 +29,6 @@ import {deleteImageFromS3,getImageUploadUrl,} from "@/lib/storage/image-upload";-import { getEmailClient } from "@/utils/emails";import {createRateLimitMiddleware,privateProcedure,@@ -441,13 +442,11 @@ export const spaces = router({},});- const emailClient = await getEmailClient({- locale: existingUser?.locale ?? ctx.user.locale,- });-try {- await emailClient.sendTemplate("SpaceInviteEmail", {+ await sendSpaceInviteEmail({to: input.email,+ locale: existingUser?.locale ?? ctx.user.locale,+ branding: await getInstanceBranding(),props: {spaceName: ctx.space.name,inviterName: ctx.user.name,diff --git a/apps/web/src/trpc/routers/user.ts b/apps/web/src/trpc/routers/user.tsindex 81ecaf0f8..1da56b9f3 100644--- a/apps/web/src/trpc/routers/user.ts+++ b/apps/web/src/trpc/routers/user.ts@@ -1,8 +1,11 @@import { subject } from "@casl/ability";import { prisma } from "@rallly/database";+import { sendRawEmail } from "@rallly/emails";+import { sendChangeEmailRequest } from "@rallly/emails/templates/change-email-request";import { absoluteUrl } from "@rallly/utils/absolute-url";import { TRPCError } from "@trpc/server";import * as z from "zod";+import { getInstanceBranding } from "@/emails/branding";import { posthog } from "@/features/analytics/posthog";import { feedbackSchema } from "@/features/feedback/schema";import { defaultNotificationPreferences } from "@/features/notifications/constants";@@ -13,7 +16,6 @@ import {deleteImageFromS3,getImageUploadUrl,} from "@/lib/storage/image-upload";-import { getEmailClient } from "@/utils/emails";import { createToken } from "@/utils/session";import { timezoneSchema } from "@/utils/timezone-schema";import {@@ -115,12 +117,10 @@ export const user = router({},);- const emailClient = await getEmailClient({- locale: currentUser.locale ?? undefined,- });-- emailClient.sendTemplate("ChangeEmailRequest", {+ sendChangeEmailRequest({to: input.email,+ locale: currentUser.locale ?? undefined,+ branding: await getInstanceBranding(),props: {verificationUrl: absoluteUrl(`/api/user/verify-email-change?token=${token}`,@@ -297,8 +297,7 @@ export const user = router({.use(createRateLimitMiddleware("submit_feedback", 5, "1 h")).input(feedbackSchema).mutation(async ({ input, ctx }) => {- const emailClient = await getEmailClient();- emailClient.sendEmail({+ sendRawEmail({to: "[email protected]",replyTo: ctx.user.email ?? undefined,subject: "Feedback",diff --git a/apps/web/src/utils/emails.ts b/apps/web/src/utils/emails.tsdeleted file mode 100644index 99e4e1d5f..000000000--- a/apps/web/src/utils/emails.ts+++ /dev/null@@ -1,44 +0,0 @@-import type { SupportedEmailProviders } from "@rallly/emails";-import { EmailClient } from "@rallly/emails";-import { createLogger } from "@rallly/logger";-import { absoluteUrl } from "@rallly/utils/absolute-url";-import * as Sentry from "@sentry/nextjs";--import { env } from "@/env";-import { getInstanceBrandingConfig } from "@/features/branding/queries";--const logger = createLogger("emails");--export const getEmailClient = async (options?: {- locale?: string;- primaryColor?: string;- logoUrl?: string;-}) => {- const brandingConfig = await getInstanceBrandingConfig();-- return new EmailClient({- provider: {- name: (process.env.EMAIL_PROVIDER as SupportedEmailProviders) ?? "smtp",- },- mail: {- from: {- name: env.NOREPLY_EMAIL_NAME,- address: env.NOREPLY_EMAIL || env.SUPPORT_EMAIL,- },- },- config: {- logoUrl: options?.logoUrl ?? brandingConfig.logoIcon,- baseUrl: absoluteUrl(),- domain: absoluteUrl().replace(/(^\w+:|^)\/\//, ""),- supportEmail: env.SUPPORT_EMAIL,- primaryColor: options?.primaryColor ?? brandingConfig.primaryColor.light,- appName: brandingConfig.appName,- hideAttribution: brandingConfig.hideAttribution,- },- locale: options?.locale,- onError: (e) => {- logger.error({ error: e }, "Email client error");- Sentry.captureException(e);- },- });-};diff --git a/packages/emails/package.json b/packages/emails/package.jsonindex fe8650931..0b5e2e869 100644--- a/packages/emails/package.json+++ b/packages/emails/package.json@@ -9,11 +9,14 @@},"exports": {".": "./src/index.ts",+ "./templates/*": "./src/templates/*.tsx","./locales/*": "./locales/en/*.json"},"dependencies": {"@aws-sdk/client-ses": "^3.501.0","@aws-sdk/credential-provider-node": "^3.501.0",+ "@rallly/logger": "workspace:*",+ "@rallly/utils": "workspace:*","@react-email/components": "^0.0.36","@react-email/render": "^1.0.6","i18next": "^26.3.0",@@ -27,7 +30,6 @@"devDependencies": {"@rallly/tailwind-config": "workspace:*","@rallly/tsconfig": "workspace:*",- "@rallly/utils": "workspace:*","@react-email/preview-server": "5.2.7","@types/nodemailer": "^6.4.14","i18next-cli": "^1.58.1",diff --git a/packages/emails/src/components/email-context.tsx b/packages/emails/src/components/email-context.tsxindex 293074b00..852b817e2 100644--- a/packages/emails/src/components/email-context.tsx+++ b/packages/emails/src/components/email-context.tsx@@ -14,4 +14,6 @@ export const previewEmailContext: EmailContext = {i18n: i18nInstance,t: i18nInstance.getFixedT("en"),appName: "Rallly",+ primaryColor: "#4f46e5",+ hideAttribution: false,};diff --git a/packages/emails/src/create-email-template.tsx b/packages/emails/src/create-email-template.tsxnew file mode 100644index 000000000..cfbf29175--- /dev/null+++ b/packages/emails/src/create-email-template.tsx@@ -0,0 +1,61 @@+import { absoluteUrl } from "@rallly/utils/absolute-url";++import { createEmailI18n } from "./i18n";+import type { EmailAttachments, IcalEvent } from "./send";+import { sendEmail } from "./send";+import type { EmailBranding, EmailContext } from "./types";++type From = { name: string; address: string };++type TemplateProps<C> = C extends (props: infer P) => React.ReactNode+ ? Omit<P, "ctx">+ : never;++type SendArgs<C> = {+ to: string;+ locale?: string;+ branding: EmailBranding;+ props: TemplateProps<C>;+ from?: From;+ attachments?: EmailAttachments;+ icalEvent?: IcalEvent;+};++/**+ * Defines a sendable email from a template component + subject. Returns a single+ * `send` function: the caller passes `branding` (instance or space) and `props`,+ * and the package resolves env constants, assembles i18n, renders, and dispatches.+ * No awareness of react-email/nodemailer/i18n leaks to callers.+ */+export function createEmailTemplate<+ C extends (props: never) => React.ReactNode,+>(definition: {+ component: C;+ subject: (props: TemplateProps<C>, ctx: EmailContext) => string;+}) {+ return async function send(args: SendArgs<C>) {+ const url = absoluteUrl();+ const { i18n, t } = await createEmailI18n(args.locale ?? "en");+ const ctx: EmailContext = {+ ...args.branding,+ baseUrl: url,+ domain: url.replace(/(^\w+:|^)\/\//, ""),+ supportEmail: process.env.SUPPORT_EMAIL ?? "",+ i18n,+ t,+ };++ return sendEmail({+ to: args.to,+ component: definition.component as unknown as (+ props: TemplateProps<C> & { ctx: EmailContext },+ ) => React.ReactNode,+ props: args.props,+ ctx,+ subject: definition.subject(args.props, ctx),+ from: args.from,+ attachments: args.attachments,+ icalEvent: args.icalEvent,+ });+ };+}diff --git a/packages/emails/src/i18n.ts b/packages/emails/src/i18n.tsindex 3de45793e..a3d40eae2 100644--- a/packages/emails/src/i18n.ts+++ b/packages/emails/src/i18n.ts@@ -26,4 +26,16 @@ const i18nDefaultConfig: InitOptions = {export type I18nInstance = typeof i18nInstance;+/**+ * Initialises the email i18n instance for `locale` and returns the instance+ * plus a locale-pinned `t`. `getFixedT(locale)` is concurrency-safe even though+ * the instance is shared — it captures the locale regardless of the instance's+ * current `language`. (Whether to swap the shared singleton for a per-send+ * `createInstance()` is tracked in RAL-1219.)+ */+export async function createEmailI18n(locale: string) {+ await i18nInstance.init({ ...i18nDefaultConfig, lng: locale });+ return { i18n: i18nInstance, t: i18nInstance.getFixedT(locale) };+}+export { i18nDefaultConfig, i18nInstance };diff --git a/packages/emails/src/index.ts b/packages/emails/src/index.tsindex b31c9a76c..747a1c8c3 100644--- a/packages/emails/src/index.ts+++ b/packages/emails/src/index.ts@@ -1,2 +1,11 @@-export type { SupportedEmailProviders } from "./send-email";-export { EmailClient } from "./send-email";+// Public surface of @rallly/emails. The package abstracts react-email,+// nodemailer, and i18n. Send a templated email via the per-template+// `sendXEmail()` functions from `@rallly/emails/templates/<name>`, passing the+// `branding` to use (instance or space). `sendRawEmail` covers plain sends.+export {+ type EmailAttachments,+ type IcalEvent,+ type SendRawEmailOptions,+ sendRawEmail,+} from "./send";+export type { EmailBranding } from "./types";diff --git a/packages/emails/src/previews/new-poll.tsx b/packages/emails/src/previews/new-poll.tsxindex 717426442..0f7656675 100644--- a/packages/emails/src/previews/new-poll.tsx+++ b/packages/emails/src/previews/new-poll.tsx@@ -1,5 +1,5 @@import { previewEmailContext } from "../components/email-context";-import NewPollEmail from "../templates/new-poll";+import { NewPollEmail } from "../templates/new-poll";export default function NewPollPreview() {return (diff --git a/packages/emails/src/send-email.tsx b/packages/emails/src/send-email.tsxdeleted file mode 100644index 0ab5adf65..000000000--- a/packages/emails/src/send-email.tsx+++ /dev/null@@ -1,220 +0,0 @@-import * as aws from "@aws-sdk/client-ses";-import { defaultProvider } from "@aws-sdk/credential-provider-node";-import { render } from "@react-email/render";-import type { Transporter } from "nodemailer";-import { createTransport } from "nodemailer";-import type Mail from "nodemailer/lib/mailer";--import { i18nDefaultConfig, i18nInstance } from "./i18n";-import { templates } from "./templates";-import type { TemplateComponent, TemplateName, TemplateProps } from "./types";--type SendEmailOptions<T extends TemplateName> = {- to: string;- from?: {- name: string;- address: string;- };- props: TemplateProps<T>;- attachments?: Mail.Options["attachments"];- icalEvent?: Mail.Options["icalEvent"];-};--type EmailProviderConfig =- | {- name: "ses";- // config defined through env vars- }- | {- name: "smtp";- // config defined through env vars- };--export type SupportedEmailProviders = EmailProviderConfig["name"];--type EmailClientConfig = {- /**- * Email provider config- */- provider: EmailProviderConfig;- /**- * Mail config- */- mail: {- from: {- name: string;- address: string;- };- };- /**- * Context to pass to each email- */- config: {- logoUrl: string;- baseUrl: string;- domain: string;- supportEmail: string;- primaryColor: string;- appName: string;- hideAttribution: boolean;- };-- locale?: string;- onError?: (error: Error) => void;-};--export class EmailClient {- private config: EmailClientConfig;- private cachedTransport?: Transporter;-- constructor(config: EmailClientConfig) {- this.config = config;- }-- async sendTemplate<T extends TemplateName>(- templateName: T,- options: SendEmailOptions<T>,- ) {- const locale = this.config.locale ?? "en";-- await i18nInstance.init({- ...i18nDefaultConfig,- lng: locale,- });-- const ctx = {- ...this.config.config,- i18n: i18nInstance,- t: i18nInstance.getFixedT(locale),- };-- const Template = templates[templateName] as TemplateComponent<T>;- const subject = Template.getSubject?.(options.props, ctx);- const component = (- <Template- // biome-ignore lint/suspicious/noExplicitAny: Fix this later- {...(options.props as any)}- ctx={ctx}- />- );-- const [html, text] = await Promise.all([- render(component),- render(component, { plainText: true }),- ]);-- try {- await this.sendEmail({- from: options.from || this.config.mail.from,- to: options.to,- subject,- html,- text,- attachments: options.attachments,- icalEvent: options.icalEvent,- });- } catch (e) {- const enhancedError = new Error(- `Failed to send email template: ${templateName}`,- {- cause: e instanceof Error ? e : new Error(String(e)),- },- );- Object.assign(enhancedError, {- templateName,- recipient: options.to,- subject,- });- this.config.onError?.(enhancedError);- }- }-- async sendEmail(options: Mail.Options) {- if (!process.env.SUPPORT_EMAIL) {- console.info("ℹ SUPPORT_EMAIL not configured - skipping email send");- return;- }-- try {- await this.transport.sendMail({- ...options,- from: options.from || this.config.mail.from,- });- return;- } catch (e) {- console.error("Error sending email", e);- }- }-- private get transport() {- if (this.cachedTransport) {- // Reuse the transport if it exists- return this.cachedTransport;- }-- switch (this.config.provider.name) {- case "ses": {- const ses = new aws.SES({- region: process.env["AWS" + "_REGION"] as string,- credentialDefaultProvider: defaultProvider,- });-- this.cachedTransport = createTransport({- SES: {- ses,- aws,- },- sendingRate: 10,- });- break;- }- case "smtp": {- const hasAuth = process.env.SMTP_USER || process.env.SMTP_PWD;- const port = process.env.SMTP_PORT- ? Number.parseInt(process.env.SMTP_PORT, 10)- : undefined;-- const secure = process.env.SMTP_SECURE === "true";-- // Log deprecation warning for legacy variable- if (process.env.SMTP_TLS_ENABLED === "true") {- console.warn(- "⚠️ SMTP_TLS_ENABLED is deprecated and no longer affects certificate validation. Use SMTP_REJECT_UNAUTHORIZED instead.",- );- }-- const rejectUnauthorized =- process.env.SMTP_REJECT_UNAUTHORIZED !== "false";-- // Warn about security change if no explicit setting- if (- process.env.SMTP_REJECT_UNAUTHORIZED === undefined &&- process.env.SMTP_TLS_ENABLED === undefined- ) {- console.warn(- "⚠️ Certificate validation is now enabled by default for SMTP connections. Set SMTP_REJECT_UNAUTHORIZED=true to silence this warning, or SMTP_REJECT_UNAUTHORIZED=false if using self-signed certificates.",- );- }-- this.cachedTransport = createTransport({- host: process.env.SMTP_HOST,- port,- secure,- auth: hasAuth- ? {- user: process.env.SMTP_USER,- pass: process.env.SMTP_PWD,- }- : undefined,- tls: {- rejectUnauthorized,- servername: process.env.SMTP_TLS_SERVERNAME,- },- });- break;- }- }-- return this.cachedTransport;- }-}diff --git a/packages/emails/src/send.tsx b/packages/emails/src/send.tsxnew file mode 100644index 000000000..ae27c1042--- /dev/null+++ b/packages/emails/src/send.tsx@@ -0,0 +1,116 @@+import { createLogger } from "@rallly/logger";+import { render } from "@react-email/render";+import type Mail from "nodemailer/lib/mailer";++import { getTransport } from "./transport";+import type { EmailContext } from "./types";++const logger = createLogger("emails");++export type EmailAttachments = Mail.Options["attachments"];+export type IcalEvent = Mail.Options["icalEvent"];+type From = { name: string; address: string };++function resolveFrom(from?: From): From {+ return (+ from ?? {+ name: process.env.NOREPLY_EMAIL_NAME ?? "Rallly",+ address: process.env.NOREPLY_EMAIL || process.env.SUPPORT_EMAIL || "",+ }+ );+}++type DispatchOptions = {+ to: string;+ from?: From;+ replyTo?: string;+ subject?: string;+ html?: string;+ text?: string;+ attachments?: EmailAttachments;+ icalEvent?: IcalEvent;+ errorLabel: string;+};++async function dispatch(options: DispatchOptions) {+ if (!process.env.SUPPORT_EMAIL) {+ logger.info("SUPPORT_EMAIL not configured - skipping email send");+ return;+ }++ try {+ await getTransport().sendMail({+ from: resolveFrom(options.from),+ to: options.to,+ replyTo: options.replyTo,+ subject: options.subject,+ html: options.html,+ text: options.text,+ attachments: options.attachments,+ icalEvent: options.icalEvent,+ });+ } catch (e) {+ // Operational (SMTP/transport) failures are logged, not thrown — sending is+ // fire-and-forget. Render/template (code) errors are NOT caught here, so they+ // propagate to the caller's error reporting (Sentry via onRequestError).+ logger.error(+ { error: e, recipient: options.to, subject: options.subject },+ `Failed to send email: ${options.errorLabel}`,+ );+ }+}++/**+ * Internal: render a template component to html + plain text and dispatch.+ * Used by `createEmailTemplate` — not part of the public API.+ */+export async function sendEmail<P extends object>(options: {+ to: string;+ component: (props: P & { ctx: EmailContext }) => React.ReactNode;+ props: P;+ ctx: EmailContext;+ subject: string;+ from?: From;+ attachments?: EmailAttachments;+ icalEvent?: IcalEvent;+}) {+ const Component = options.component as unknown as (+ props: P & { ctx: EmailContext },+ ) => React.ReactNode;+ const element = <Component {...options.props} ctx={options.ctx} />;++ const [html, text] = await Promise.all([+ render(element),+ render(element, { plainText: true }),+ ]);++ await dispatch({+ to: options.to,+ from: options.from,+ subject: options.subject,+ html,+ text,+ attachments: options.attachments,+ icalEvent: options.icalEvent,+ errorLabel: options.subject,+ });+}++export type SendRawEmailOptions = {+ to: string;+ subject: string;+ text?: string;+ html?: string;+ from?: From;+ replyTo?: string;+ attachments?: EmailAttachments;+ icalEvent?: IcalEvent;+};++/**+ * Sends a plain (non-template) email — subject + text/html, no rendering.+ * For the rare app-specific cases that don't warrant a React template.+ */+export async function sendRawEmail(options: SendRawEmailOptions) {+ await dispatch({ ...options, errorLabel: options.subject });+}diff --git a/packages/emails/src/templates.ts b/packages/emails/src/templates.tsdeleted file mode 100644index 9f37deeaa..000000000--- a/packages/emails/src/templates.ts+++ /dev/null@@ -1,36 +0,0 @@-import { AbandonedCheckoutEmail } from "./templates/abandoned-checkout";-import { ChangeEmailRequest } from "./templates/change-email-request";-import { EventCanceledEmail } from "./templates/event-canceled";-import { FinalizeHostEmail } from "./templates/finalized-host";-import { FinalizeParticipantEmail } from "./templates/finalized-participant";-import { LicenseKeyEmail } from "./templates/license-key";-import { NewCommentEmail } from "./templates/new-comment";-import { NewParticipantEmail } from "./templates/new-participant";-import { NewParticipantConfirmationEmail } from "./templates/new-participant-confirmation";-import { NewPollEmail } from "./templates/new-poll";-import { RegisterEmail } from "./templates/register";-import { ResetPasswordEmail } from "./templates/reset-password";-import { SpaceInviteEmail } from "./templates/space-invite";-import type { TemplateName } from "./types";--const templates = {- FinalizeHostEmail,- FinalizeParticipantEmail,- NewCommentEmail,- NewParticipantEmail,- NewParticipantConfirmationEmail,- NewPollEmail,- RegisterEmail,- ResetPasswordEmail,- ChangeEmailRequest,- AbandonedCheckoutEmail,- LicenseKeyEmail,- EventCanceledEmail,- SpaceInviteEmail,-};--export const emailTemplates = Object.keys(templates) as TemplateName[];--export type EmailTemplates = typeof templates;--export { templates };diff --git a/packages/emails/src/templates/change-email-request.tsx b/packages/emails/src/templates/change-email-request.tsxindex f13279d92..fd4978234 100644--- a/packages/emails/src/templates/change-email-request.tsx+++ b/packages/emails/src/templates/change-email-request.tsx@@ -3,6 +3,7 @@ import { Trans } from "react-i18next/TransWithoutContext";import { EmailLayout } from "../components/email-layout";import { Button, Heading, Text } from "../components/styled-components";+import { createEmailTemplate } from "../create-email-template";import type { EmailContext } from "../types";interface ChangeEmailRequestProps {@@ -69,14 +70,11 @@ export const ChangeEmailRequest = ({);};-ChangeEmailRequest.getSubject = (- _props: ChangeEmailRequestProps,- ctx: EmailContext,-) => {- return ctx.t("changeEmailRequest_subject", {- defaultValue: "Verify your new email address",- ns: "emails",- });-};--export default ChangeEmailRequest;+export const sendChangeEmailRequest = createEmailTemplate({+ component: ChangeEmailRequest,+ subject: (_props, ctx) =>+ ctx.t("changeEmailRequest_subject", {+ defaultValue: "Verify your new email address",+ ns: "emails",+ }),+});diff --git a/packages/emails/src/templates/event-canceled.tsx b/packages/emails/src/templates/event-canceled.tsxindex 5eb1591ff..b0e19cc1d 100644--- a/packages/emails/src/templates/event-canceled.tsx+++ b/packages/emails/src/templates/event-canceled.tsx@@ -3,6 +3,7 @@ import { Trans } from "react-i18next/TransWithoutContext";import { EmailLayout } from "../components/email-layout";import { borderColor, Heading, Text } from "../components/styled-components";+import { createEmailTemplate } from "../create-email-template";import type { EmailContext } from "../types";export interface EventCanceledEmailProps {@@ -93,15 +94,14 @@ const EventCanceledEmail = ({);};-EventCanceledEmail.getSubject = (- props: EventCanceledEmailProps,- ctx: EmailContext,-) => {- return ctx.t("eventCanceledSubject", {- defaultValue: "Canceled: {title}",- title: props.title,- ns: "emails",- });-};-export { EventCanceledEmail };++export const sendEventCanceledEmail = createEmailTemplate({+ component: EventCanceledEmail,+ subject: (props, ctx) =>+ ctx.t("eventCanceledSubject", {+ defaultValue: "Canceled: {title}",+ title: props.title,+ ns: "emails",+ }),+});diff --git a/packages/emails/src/templates/finalized-host.tsx b/packages/emails/src/templates/finalized-host.tsxindex 7390a9565..81dce7071 100644--- a/packages/emails/src/templates/finalized-host.tsx+++ b/packages/emails/src/templates/finalized-host.tsx@@ -8,6 +8,7 @@ import {Heading,Text,} from "../components/styled-components";+import { createEmailTemplate } from "../create-email-template";import type { EmailContext } from "../types";export interface FinalizeHostEmailProps {@@ -118,15 +119,14 @@ const FinalizeHostEmail = ({);};-FinalizeHostEmail.getSubject = (- props: FinalizeHostEmailProps,- ctx: EmailContext,-) => {- return ctx.t("finalizeHost_subject", {- defaultValue: "Date booked for {title}",- title: props.title,- ns: "emails",- });-};-export { FinalizeHostEmail };++export const sendFinalizeHostEmail = createEmailTemplate({+ component: FinalizeHostEmail,+ subject: (props, ctx) =>+ ctx.t("finalizeHost_subject", {+ defaultValue: "Date booked for {title}",+ title: props.title,+ ns: "emails",+ }),+});diff --git a/packages/emails/src/templates/finalized-participant.tsx b/packages/emails/src/templates/finalized-participant.tsxindex 580f1ae73..d14ae5a7e 100644--- a/packages/emails/src/templates/finalized-participant.tsx+++ b/packages/emails/src/templates/finalized-participant.tsx@@ -8,6 +8,7 @@ import {Heading,Text,} from "../components/styled-components";+import { createEmailTemplate } from "../create-email-template";import type { EmailContext } from "../types";export interface FinalizeParticipantEmailProps {@@ -116,15 +117,14 @@ const FinalizeParticipantEmail = ({);};-FinalizeParticipantEmail.getSubject = (- props: FinalizeParticipantEmailProps,- ctx: EmailContext,-) => {- return ctx.t("finalizeParticipant_subject", {- defaultValue: "Date booked for {title}",- title: props.title,- ns: "emails",- });-};-export { FinalizeParticipantEmail };++export const sendFinalizeParticipantEmail = createEmailTemplate({+ component: FinalizeParticipantEmail,+ subject: (props, ctx) =>+ ctx.t("finalizeParticipant_subject", {+ defaultValue: "Date booked for {title}",+ title: props.title,+ ns: "emails",+ }),+});diff --git a/packages/emails/src/templates/license-key.tsx b/packages/emails/src/templates/license-key.tsxindex 7c6a10f81..06008fa1c 100644--- a/packages/emails/src/templates/license-key.tsx+++ b/packages/emails/src/templates/license-key.tsx@@ -2,6 +2,7 @@ import { Trans } from "react-i18next/TransWithoutContext";import { EmailLayout } from "../components/email-layout";import { Heading, Link, Text } from "../components/styled-components";+import { createEmailTemplate } from "../create-email-template";import type { EmailContext } from "../types";interface LicenseKeyEmailProps {@@ -157,15 +158,12 @@ export const LicenseKeyEmail = ({);};-LicenseKeyEmail.getSubject = (- props: LicenseKeyEmailProps,- ctx: EmailContext,-) => {- return ctx.t("license_key_subject", {- defaultValue: "Your Rallly Self-Hosted {tier} License",- ns: "emails",- tier: props.tier,- });-};--export default LicenseKeyEmail;+export const sendLicenseKeyEmail = createEmailTemplate({+ component: LicenseKeyEmail,+ subject: (props, ctx) =>+ ctx.t("license_key_subject", {+ defaultValue: "Your Rallly Self-Hosted {tier} License",+ ns: "emails",+ tier: props.tier,+ }),+});diff --git a/packages/emails/src/templates/new-comment.tsx b/packages/emails/src/templates/new-comment.tsxindex 62d8d46b1..3b71c4bb6 100644--- a/packages/emails/src/templates/new-comment.tsx+++ b/packages/emails/src/templates/new-comment.tsx@@ -3,7 +3,7 @@ import { Trans } from "react-i18next/TransWithoutContext";import type { NotificationBaseProps } from "../components/notification-email";import NotificationEmail from "../components/notification-email";import { Heading, Text } from "../components/styled-components";-import type { EmailContext } from "../types";+import { createEmailTemplate } from "../create-email-template";export interface NewCommentEmailProps extends NotificationBaseProps {authorName: string;@@ -54,16 +54,15 @@ const NewCommentEmail = ({);};-NewCommentEmail.getSubject = (- props: NewCommentEmailProps,- ctx: EmailContext,-) => {- return ctx.t("newComment_subject", {- ns: "emails",- defaultValue: "{authorName} has commented on {title}",- authorName: props.authorName,- title: props.title,- });-};-export { NewCommentEmail };++export const sendNewCommentEmail = createEmailTemplate({+ component: NewCommentEmail,+ subject: (props, ctx) =>+ ctx.t("newComment_subject", {+ ns: "emails",+ defaultValue: "{authorName} has commented on {title}",+ authorName: props.authorName,+ title: props.title,+ }),+});diff --git a/packages/emails/src/templates/new-participant-confirmation.tsx b/packages/emails/src/templates/new-participant-confirmation.tsxindex 3d037e65f..5eb4cf14a 100644--- a/packages/emails/src/templates/new-participant-confirmation.tsx+++ b/packages/emails/src/templates/new-participant-confirmation.tsx@@ -8,6 +8,7 @@ import {Section,Text,} from "../components/styled-components";+import { createEmailTemplate } from "../create-email-template";import type { EmailContext } from "../types";interface NewParticipantConfirmationEmailProps {@@ -90,15 +91,14 @@ const NewParticipantConfirmationEmail = ({);};-NewParticipantConfirmationEmail.getSubject = (- props: NewParticipantConfirmationEmailProps,- ctx: EmailContext,-) => {- return ctx.t("newParticipantConfirmation_subject", {- defaultValue: "Thanks for responding to {title}",- title: props.title,- ns: "emails",- });-};-export { NewParticipantConfirmationEmail };++export const sendNewParticipantConfirmationEmail = createEmailTemplate({+ component: NewParticipantConfirmationEmail,+ subject: (props, ctx) =>+ ctx.t("newParticipantConfirmation_subject", {+ defaultValue: "Thanks for responding to {title}",+ title: props.title,+ ns: "emails",+ }),+});diff --git a/packages/emails/src/templates/new-participant.tsx b/packages/emails/src/templates/new-participant.tsxindex 0b9f98409..9de194236 100644--- a/packages/emails/src/templates/new-participant.tsx+++ b/packages/emails/src/templates/new-participant.tsx@@ -3,7 +3,7 @@ import { Trans } from "react-i18next/TransWithoutContext";import type { NotificationBaseProps } from "../components/notification-email";import NotificationEmail from "../components/notification-email";import { Heading, Text } from "../components/styled-components";-import type { EmailContext } from "../types";+import { createEmailTemplate } from "../create-email-template";export interface NewParticipantEmailProps extends NotificationBaseProps {participantName: string;@@ -59,16 +59,15 @@ const NewParticipantEmail = ({);};-NewParticipantEmail.getSubject = (- props: NewParticipantEmailProps,- ctx: EmailContext,-) => {- return ctx.t("newParticipant_subject", {- defaultValue: "{name} has responded to {title}",- name: props.participantName,- title: props.title,- ns: "emails",- });-};-export { NewParticipantEmail };++export const sendNewParticipantEmail = createEmailTemplate({+ component: NewParticipantEmail,+ subject: (props, ctx) =>+ ctx.t("newParticipant_subject", {+ defaultValue: "{name} has responded to {title}",+ name: props.participantName,+ title: props.title,+ ns: "emails",+ }),+});diff --git a/packages/emails/src/templates/new-poll.tsx b/packages/emails/src/templates/new-poll.tsxindex ca87867d5..b6c8e3529 100644--- a/packages/emails/src/templates/new-poll.tsx+++ b/packages/emails/src/templates/new-poll.tsx@@ -8,6 +8,7 @@ import {Link,Text,} from "../components/styled-components";+import { createEmailTemplate } from "../create-email-template";import type { EmailContext } from "../types";export interface NewPollEmailProps {@@ -69,12 +70,12 @@ export const NewPollEmail = ({);};-NewPollEmail.getSubject = (props: NewPollEmailProps, ctx: EmailContext) => {- return ctx.t("newPoll_subject", {- defaultValue: "Let's find a date for {title}!",- title: props.title,- ns: "emails",- });-};--export default NewPollEmail;+export const sendNewPollEmail = createEmailTemplate({+ component: NewPollEmail,+ subject: (props, ctx) =>+ ctx.t("newPoll_subject", {+ defaultValue: "Let's find a date for {title}!",+ title: props.title,+ ns: "emails",+ }),+});diff --git a/packages/emails/src/templates/register.tsx b/packages/emails/src/templates/register.tsxindex 1ef77a64a..869c384d3 100644--- a/packages/emails/src/templates/register.tsx+++ b/packages/emails/src/templates/register.tsx@@ -10,6 +10,7 @@ import {Text,trackingWide,} from "../components/styled-components";+import { createEmailTemplate } from "../create-email-template";import type { EmailContext } from "../types";interface RegisterEmailProps {@@ -84,11 +85,11 @@ export const RegisterEmail = ({ code, ctx }: RegisterEmailProps) => {);};-RegisterEmail.getSubject = (_props: RegisterEmailProps, ctx: EmailContext) => {- return ctx.t("register_subject", {- defaultValue: "Please verify your email address",- ns: "emails",- });-};--export default RegisterEmail;+export const sendRegisterEmail = createEmailTemplate({+ component: RegisterEmail,+ subject: (_props, ctx) =>+ ctx.t("register_subject", {+ defaultValue: "Please verify your email address",+ ns: "emails",+ }),+});diff --git a/packages/emails/src/templates/reset-password.tsx b/packages/emails/src/templates/reset-password.tsxindex 690c22080..87e080dfc 100644--- a/packages/emails/src/templates/reset-password.tsx+++ b/packages/emails/src/templates/reset-password.tsx@@ -3,6 +3,7 @@ import { Trans } from "react-i18next/TransWithoutContext";import { EmailLayout } from "../components/email-layout";import { Button, Heading, Link, Text } from "../components/styled-components";+import { createEmailTemplate } from "../create-email-template";import type { EmailContext } from "../types";interface ResetPasswordEmailProps {@@ -68,14 +69,11 @@ export const ResetPasswordEmail = ({);};-ResetPasswordEmail.getSubject = (- _props: ResetPasswordEmailProps,- ctx: EmailContext,-) => {- return ctx.t("resetPassword_subject", {- defaultValue: "Reset your password",- ns: "emails",- });-};--export default ResetPasswordEmail;+export const sendResetPasswordEmail = createEmailTemplate({+ component: ResetPasswordEmail,+ subject: (_props, ctx) =>+ ctx.t("resetPassword_subject", {+ defaultValue: "Reset your password",+ ns: "emails",+ }),+});diff --git a/packages/emails/src/templates/space-invite.tsx b/packages/emails/src/templates/space-invite.tsxindex 41b987741..d8eb626aa 100644--- a/packages/emails/src/templates/space-invite.tsx+++ b/packages/emails/src/templates/space-invite.tsx@@ -3,6 +3,7 @@ import { Trans } from "react-i18next/TransWithoutContext";import { EmailLayout } from "../components/email-layout";import { Button, Heading, Text } from "../components/styled-components";+import { createEmailTemplate } from "../create-email-template";import type { EmailContext } from "../types";interface SpaceInviteEmailProps {@@ -55,14 +56,12 @@ export const SpaceInviteEmail = ({</EmailLayout>);-SpaceInviteEmail.getSubject = (- props: SpaceInviteEmailProps,- ctx: EmailContext,-) =>- ctx.t("spaceInvite_subject", {- defaultValue: "You're invited to join {spaceName}",- spaceName: props.spaceName,- ns: "emails",- });--export default SpaceInviteEmail;+export const sendSpaceInviteEmail = createEmailTemplate({+ component: SpaceInviteEmail,+ subject: (props, ctx) =>+ ctx.t("spaceInvite_subject", {+ defaultValue: "You're invited to join {spaceName}",+ spaceName: props.spaceName,+ ns: "emails",+ }),+});diff --git a/packages/emails/src/transport.ts b/packages/emails/src/transport.tsnew file mode 100644index 000000000..9520bbb9f--- /dev/null+++ b/packages/emails/src/transport.ts@@ -0,0 +1,85 @@+import * as aws from "@aws-sdk/client-ses";+import { defaultProvider } from "@aws-sdk/credential-provider-node";+import type { Transporter } from "nodemailer";+import { createTransport } from "nodemailer";++type EmailProvider = "ses" | "smtp";++export type SupportedEmailProviders = EmailProvider;++let cachedTransport: Transporter | undefined;++function createTransportForProvider(provider: EmailProvider): Transporter {+ switch (provider) {+ case "ses": {+ const ses = new aws.SES({+ region: process.env["AWS" + "_REGION"] as string,+ credentialDefaultProvider: defaultProvider,+ });++ return createTransport({+ SES: { ses, aws },+ sendingRate: 10,+ });+ }+ case "smtp": {+ const hasAuth = process.env.SMTP_USER || process.env.SMTP_PWD;+ const port = process.env.SMTP_PORT+ ? Number.parseInt(process.env.SMTP_PORT, 10)+ : undefined;++ const secure = process.env.SMTP_SECURE === "true";++ // Log deprecation warning for legacy variable+ if (process.env.SMTP_TLS_ENABLED === "true") {+ console.warn(+ "⚠️ SMTP_TLS_ENABLED is deprecated and no longer affects certificate validation. Use SMTP_REJECT_UNAUTHORIZED instead.",+ );+ }++ const rejectUnauthorized =+ process.env.SMTP_REJECT_UNAUTHORIZED !== "false";++ // Warn about security change if no explicit setting+ if (+ process.env.SMTP_REJECT_UNAUTHORIZED === undefined &&+ process.env.SMTP_TLS_ENABLED === undefined+ ) {+ console.warn(+ "⚠️ Certificate validation is now enabled by default for SMTP connections. Set SMTP_REJECT_UNAUTHORIZED=true to silence this warning, or SMTP_REJECT_UNAUTHORIZED=false if using self-signed certificates.",+ );+ }++ return createTransport({+ host: process.env.SMTP_HOST,+ port,+ secure,+ auth: hasAuth+ ? {+ user: process.env.SMTP_USER,+ pass: process.env.SMTP_PWD,+ }+ : undefined,+ tls: {+ rejectUnauthorized,+ servername: process.env.SMTP_TLS_SERVERNAME,+ },+ });+ }+ }+}++/**+ * Returns a process-wide memoized nodemailer transport, derived from+ * `EMAIL_PROVIDER` + the provider's env vars. Reused across every send in the+ * same (warm) process — unlike the previous per-`EmailClient`-instance cache,+ * which never outlived a single send.+ */+export function getTransport(): Transporter {+ if (!cachedTransport) {+ const provider =+ (process.env.EMAIL_PROVIDER as EmailProvider | undefined) ?? "smtp";+ cachedTransport = createTransportForProvider(provider);+ }+ return cachedTransport;+}diff --git a/packages/emails/src/types.ts b/packages/emails/src/types.tsindex 3a5a317e3..f5d811610 100644--- a/packages/emails/src/types.ts+++ b/packages/emails/src/types.ts@@ -1,27 +1,28 @@import type { TFunction } from "i18next";import type { I18nInstance } from "./i18n";-import type { EmailTemplates } from "./templates";-export type EmailContext = {+/**+ * The themeable part of an email — the only thing that varies between instance+ * and space branding. Passed as a prop on every send; the caller decides which+ * to use. (Deployment constants like base URL / support email are resolved by+ * the package from env, not passed.)+ */+export type EmailBranding = {+ primaryColor: string;logoUrl: string;+ appName: string;+ hideAttribution: boolean;+};++/**+ * Internal per-render context handed to template components: branding + env+ * constants + a locale-pinned i18n. Assembled inside the package.+ */+export type EmailContext = EmailBranding & {baseUrl: string;domain: string;supportEmail: string;i18n: I18nInstance;t: TFunction;- appName: string;- primaryColor?: string;- hideAttribution?: boolean;-};--export type TemplateName = keyof EmailTemplates;--export type TemplateProps<T extends TemplateName> = Omit<- React.ComponentProps<EmailTemplates[T]>,- "ctx"->;--export type TemplateComponent<T extends TemplateName> = EmailTemplates[T] & {- getSubject?: (props: TemplateProps<T>, ctx: EmailContext) => string;};diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 79ca60ce1..f9a5977dd 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -677,6 +677,12 @@ importers:'@aws-sdk/credential-provider-node':specifier: ^3.501.0version: 3.972.5+ '@rallly/logger':+ specifier: workspace:*+ version: link:../logger+ '@rallly/utils':+ specifier: workspace:*+ version: link:../utils'@react-email/components':specifier: ^0.0.36@@ -711,9 +717,6 @@ importers:'@rallly/tsconfig':specifier: workspace:*version: link:../tsconfig- '@rallly/utils':- specifier: workspace:*- version: link:../utils'@react-email/preview-server':specifier: 5.2.7version: 5.2.7(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])