Files
gerbeur/api/services/email-service.ts
khannurien 7960d74c55 v4: weekly digests and monthly recaps go out by email, every email is written once as Markdown in the app's one catalog, and a review of the last two commits removes what they stated twice — users get a weekly digest (what happened to them, what the people and playlists they follow posted, the week's top dumps, the community) and a monthly recap (the month's top dumps and the community), both on by default, in their own style and scheme. digest-service sends what is due every quarter of an hour from digest_schedule (migration 0020), which holds each user's rolling 7- or 30-day period; existing users' first periods are spread over the coming week or month, a digest more than a period late covers the last full one, an empty one isn't sent, and an address like admin@localhost is skipped. Each digest carries a one-click unsubscribe (List-Unsubscribe and List-Unsubscribe-Post, POST /api/users/unsubscribe) and a link to the new /unsubscribe page, which asks before turning that cadence off, since mail scanners open every link; the token (lib/jwt) names the user and the cadence and never expires. The welcome email now says the digests are on. The emails' words moved out of a hand-written api/mail/strings.ts into the Lingui catalogs the interface uses: lingui extracts api/mail/ too, the catalogs moved to a top-level locales/ that both halves read, compile emits ES modules the server imports (api/mail/i18n.ts), messages take ICU plurals, and the labels the settings tab, the unsubscribe page and the emails share are one message each (their French had already drifted apart). Each template writes its email once as Markdown, which is the plain-text part, and EmailKit.render draws its blocks in the style (a lone link is a button, a list item starting with an image a thumbnail row, a numbered list a ranking, --- the footer), so no string is declared for an HTML and a text version; user text is escaped for Markdown, which the welcome body didn't do for usernames, whose _ read as emphasis. paint() set colors before a border-top shorthand that reset them, so every divider was black. The review also gave one home to what was written twice: the locale list (shared/locale.ts, read by lingui.config, the client, the server and its catalog loader), the base style and default scheme (shared/theme.ts), an email's look (lookOf, which digest-service, welcome and reset share), whether email is on (EMAIL_ENABLED, read by email-service and index.html), a setting's column and its default in the digests' SQL (SETTINGS_COLUMNS, DEFAULT_SETTINGS), the unsubscribe token (made once, not parsed back from a URL), AuthProvider's compare-and-store, ThemeProvider's twin style and scheme code (useThemeChoice), the test JWT encoder, and duplicate digest messages. The email palettes stay a flattened copy of the themes' tokens, now under a test that caught Times' secondary and link colors drifting. The Dockerfile copies api/mail and locales so the build extracts the emails' messages and the server finds its catalogs, and deno.json maps @lingui/core for the runtime image. 236 backend tests (new: digest building, sending, catch-up, scheduling and unsubscribing; the Markdown renderer; French from the catalog; palettes against themes; the stagger migration; unsubscribe tokens) and 661 frontend tests (new: the unsubscribe page) pass, and tsc, eslint, doc:lint, deno check, deno lint and deno fmt are clean.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 22:14:46 +00:00

77 lines
2.4 KiB
TypeScript

/**
* Sends the site's email through the SMTP server of {@link SMTPS_URL}, which
* may be unset. The welcome email, the password reset link and the digests go
* through it, each rendered first by its module in `api/mail/`. They check
* {@link isEmailEnabled} before rendering.
*
* Importing this module throws when {@link SMTPS_URL} is set without
* {@link FROM_EMAIL}, so a misconfigured server doesn't start rather than fail
* at its first send.
*
* @module
*/
import nodemailer from "nodemailer";
import { EMAIL_ENABLED, FROM_EMAIL, SMTPS_URL } from "../config.ts";
import type { RenderedEmail } from "../mail/layout.ts";
if (EMAIL_ENABLED && !FROM_EMAIL) {
throw new Error(
"GERBEUR_FROM_EMAIL environment variable is required when GERBEUR_SMTPS_URL is set.",
);
}
/**
* Passed to {@link sendEmail}: a rendered email, its recipient, and the
* headers some emails add (the digests' `List-Unsubscribe`).
*/
export interface OutgoingEmail extends RenderedEmail {
to: string;
headers?: Record<string, string>;
}
/**
* Hands a message to a mail server. nodemailer's SMTP transport is one, and
* the tests put a recording one in its place with {@link setEmailTransport}.
*/
export interface EmailTransport {
sendMail(message: OutgoingEmail & { from: string }): Promise<unknown>;
}
let transport: EmailTransport | null = EMAIL_ENABLED
? nodemailer.createTransport(SMTPS_URL)
: null;
/**
* Checks whether email can be sent. Without an SMTP server, sign-up sends no
* welcome email, a password reset request does nothing, and no digest goes
* out.
*/
export function isEmailEnabled(): boolean {
return transport !== null;
}
/**
* Replaces the transport, so that email is enabled and every message goes to
* `next`; null disables email again. The tests use it to read what was sent.
*/
export function setEmailTransport(next: EmailTransport | null): void {
transport = next;
}
/**
* Sends `email` from {@link FROM_EMAIL} and resolves once the SMTP server has
* accepted it. The welcome and reset emails don't wait for it: a slow server
* mustn't hold up the request.
*
* @throws {Error} When email is disabled, or when the server refuses the
* message or can't be reached.
*/
export async function sendEmail(email: OutgoingEmail): Promise<void> {
if (!transport) {
throw new Error("Email is disabled: GERBEUR_SMTPS_URL is unset.");
}
await transport.sendMail({ ...email, from: FROM_EMAIL });
}