diff --git a/apps/web/src/server/service/email-queue-service.ts b/apps/web/src/server/service/email-queue-service.ts index 5980720b2..c09e25259 100644 --- a/apps/web/src/server/service/email-queue-service.ts +++ b/apps/web/src/server/service/email-queue-service.ts @@ -8,6 +8,7 @@ import { sendRawEmail } from "../aws/ses"; import { getRedis, BULL_PREFIX } from "../redis"; import { DEFAULT_QUEUE_OPTIONS } from "../queue/queue-constants"; import { logger } from "../logger/log"; +import { countMailboxes } from "../utils/from-address"; import { createWorkerHandler, TeamJob } from "../queue/bullmq-context"; import { LimitService } from "./limit-service"; import { @@ -465,6 +466,15 @@ async function executeEmail(job: QueueEmailJob) { const limitCheck = await LimitService.checkEmailLimit( email.teamId, email.to, + { + id: email.id, + // Mailboxes as Nodemailer will send them, not array entries. + recipients: countMailboxes([ + ...email.to, + ...(email.cc ?? []), + ...(email.bcc ?? []), + ]), + }, ); logger.info({ limitCheck }, `[EmailQueueService]: Limit check`); if (limitCheck.isLimitReached) { diff --git a/apps/web/src/server/service/limit-service.ts b/apps/web/src/server/service/limit-service.ts index 8a0d36e66..86418ec43 100644 --- a/apps/web/src/server/service/limit-service.ts +++ b/apps/web/src/server/service/limit-service.ts @@ -2,11 +2,46 @@ import { PLAN_LIMITS, LimitReason } from "~/lib/constants/plans"; import { env } from "~/env"; import { getThisMonthUsage } from "./usage-service"; import { TeamService } from "./team-service"; -import { withCache } from "../redis"; +import { getRedis, redisKey, withCache } from "../redis"; +import { emailTeam } from "./team-email"; +import { newSenderDailyLimit, newSenderLimitEmail } from "./new-sender-ramp"; import { db } from "../db"; import { logger } from "../logger/log"; import { Plan } from "@prisma/client"; +/** + * Claims today's new-account allowance for one email's recipients. + * KEYS[1]: hash of email id -> recipients claimed, plus "__total". + * ARGV: email id, recipients, limit, ttl. A retry of the same email reuses + * its claim; concurrent workers can't both take the last of the allowance. + */ +const RESERVE_SLOT = ` +if redis.call('HEXISTS', KEYS[1], ARGV[1]) == 1 then return 1 end +local total = tonumber(redis.call('HGET', KEYS[1], '__total') or '0') +local wanted = tonumber(ARGV[2]) +if total + wanted > tonumber(ARGV[3]) then return 0 end +redis.call('HSET', KEYS[1], ARGV[1], wanted) +redis.call('HINCRBY', KEYS[1], '__total', wanted) +redis.call('EXPIRE', KEYS[1], tonumber(ARGV[4])) +return 1 +`; + +/** How long the new-account check may take before sending goes ahead without it. */ +const NEW_SENDER_CHECK_TIMEOUT_MS = 2_000; + +function withTimeout(promise: Promise, ms: number): Promise { + let timer: ReturnType | undefined; + return Promise.race([ + promise, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`timed out after ${ms}ms`)), + ms, + ); + }), + ]).finally(() => clearTimeout(timer)); +} + function isLimitExceeded(current: number, limit: number): boolean { if (limit === -1) return false; // unlimited return current >= limit; @@ -151,9 +186,103 @@ export class LimitService { // - Sends "warning" emails when nearing daily/monthly limits (rate-limited in TeamService) // - Sends "limit reached" notifications when limits are exceeded (rate-limited in TeamService) // - Teams with inactive subscriptions are treated like FREE plans for monthly limit alerts + /** + * The new-account limit for a team in its first 14 days, or null when it + * doesn't apply (older or grandfathered teams, custom limits). Lifetime + * bounce/complaint counts move slowly, so they're cached briefly. + */ + static async newSenderLimit(team: { + id: number; + createdAt?: Date | string | null; + dailyEmailLimit: number; + }): Promise { + // Cheap check first: older teams and custom limits never query anything. + if ( + newSenderDailyLimit(team, { sent: 0, hardBounced: 0, complained: 0 }) === + null + ) { + return null; + } + const counts = await withCache( + `newsender:counts:${team.id}`, + async () => { + const usage = await db.dailyEmailUsage.aggregate({ + where: { teamId: team.id }, + _sum: { sent: true, hardBounced: true, complained: true }, + }); + return { + sent: usage._sum.sent ?? 0, + hardBounced: usage._sum.hardBounced ?? 0, + complained: usage._sum.complained ?? 0, + }; + }, + { ttlSeconds: 300 }, + ); + return newSenderDailyLimit(team, counts); + } + + /** + * Atomically claims today's (UTC) allowance for this email's recipients + * (to + cc + bcc: the cap counts people emailed, like the `sent` counter). + * A retry of the same email reuses its claim. Returns false when it would + * go over the day's limit. + */ + static async reserveNewSenderSlot( + teamId: number, + emailId: string, + recipients: number, + limit: number, + /** The UTC day the check started, so a slow call can't spill into tomorrow. */ + day: string, + ) { + const claimed = await getRedis().eval( + RESERVE_SLOT, + 1, + redisKey(`newsender:recipients:${teamId}:${day}`), + emailId, + String(Math.max(1, recipients)), + String(limit), + String(2 * 24 * 60 * 60), + ); + return Number(claimed) === 1; + } + + /** Tells the team once a day that it reached its new-account limit. */ + static async notifyNewSenderLimit( + teamId: number, + teamName: string, + limit: number, + day: string, + ) { + try { + // Once per UTC day, so a notice just before midnight doesn't hide tomorrow's. + const acquired = await getRedis().set( + redisKey(`limit:notify:${teamId}:NEW_SENDER:${day}`), + "1", + "EX", + 24 * 60 * 60, + "NX", + ); + if (acquired !== "OK") return; + const message = newSenderLimitEmail({ + teamName, + limit, + settingsUrl: `${env.NEXTAUTH_URL}/settings`, + }); + await emailTeam(teamId, message.subject, message.text); + } catch (error) { + logger.warn( + { err: error, teamId }, + "[LimitService]: New-sender limit notice failed", + ); + } + } + static async checkEmailLimit( teamId: number, recipients: string[] = [], + /** The email about to be sent and its recipient count (to + cc + bcc); needed for the new-account limit. */ + email?: { id: string; recipients: number }, ): Promise<{ isLimitReached: boolean; limit: number; @@ -165,6 +294,8 @@ export class LimitService { return { isLimitReached: false, limit: -1 }; } + // The UTC day this check started; the new-account limit counts against it. + const sendDay = new Date().toISOString().slice(0, 10); const team = await TeamService.getTeamCached(teamId); // In cloud, enforce verification and block flags first @@ -219,6 +350,56 @@ export class LimitService { `[LimitService]: Daily usage and limit`, ); + // A paid team in its first 14 days starts with a lower daily limit that + // grows with clean sending, so a list can't be blasted on day one. + // If the check itself fails, sending carries on as before (logged). + if (activePlan !== "FREE" && email) { + let rampLimit: number | null = null; + let allowed = true; + try { + // Bounded: a hung Redis or DB call mustn't hold a queue worker. + const result = await withTimeout( + (async () => { + const limit = await LimitService.newSenderLimit(team); + if (limit === null) return { limit, allowed: true }; + const ok = await LimitService.reserveNewSenderSlot( + teamId, + email.id, + email.recipients, + Math.min(limit, dailyLimit), + sendDay, + ); + return { limit, allowed: ok }; + })(), + NEW_SENDER_CHECK_TIMEOUT_MS, + ); + rampLimit = result.limit; + allowed = result.allowed; + } catch (error) { + rampLimit = null; + allowed = true; + logger.error( + { err: error, teamId }, + "[LimitService]: New-account limit check failed; not applied", + ); + } + if (rampLimit !== null && !allowed) { + // In the background: a slow notice mustn't hold a queue worker. + void LimitService.notifyNewSenderLimit( + teamId, + team.name, + rampLimit, + sendDay, + ); + return { + isLimitReached: true, + limit: rampLimit, + reason: LimitReason.EMAIL_DAILY_LIMIT_REACHED, + available: 0, + }; + } + } + if (isLimitExceeded(dailyUsage, dailyLimit)) { // Notify: daily limit reached try { diff --git a/apps/web/src/server/service/limit-service.unit.test.ts b/apps/web/src/server/service/limit-service.unit.test.ts index ecdb1ea13..87dd44550 100644 --- a/apps/web/src/server/service/limit-service.unit.test.ts +++ b/apps/web/src/server/service/limit-service.unit.test.ts @@ -1,20 +1,41 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -const { mockEnv, mockGetTeamCached, mockTeamUsers } = vi.hoisted(() => ({ - mockEnv: { NEXT_PUBLIC_IS_CLOUD: true }, +const { + mockEnv, + mockGetTeamCached, + mockTeamUsers, + mockUsageAggregate, + mockRedisEval, + mockRedisSet, + mockEmailTeam, +} = vi.hoisted(() => ({ + mockEnv: { + NEXT_PUBLIC_IS_CLOUD: true, + NEXTAUTH_URL: "https://app.usesend.com", + }, mockGetTeamCached: vi.fn(), mockTeamUsers: vi.fn(), + mockUsageAggregate: vi.fn(), + mockRedisEval: vi.fn(), + mockRedisSet: vi.fn(), + mockEmailTeam: vi.fn(), })); vi.mock("~/env", () => ({ env: mockEnv })); vi.mock("~/server/db", () => ({ - db: { teamUser: { findMany: mockTeamUsers } }, + db: { + teamUser: { findMany: mockTeamUsers }, + dailyEmailUsage: { aggregate: mockUsageAggregate }, + }, })); +vi.mock("~/server/service/team-email", () => ({ emailTeam: mockEmailTeam })); vi.mock("~/server/logger/log", () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, })); vi.mock("~/server/redis", () => ({ withCache: (_key: string, fn: () => unknown) => fn(), + getRedis: () => ({ set: mockRedisSet, eval: mockRedisEval }), + redisKey: (key: string) => key, })); vi.mock("~/server/service/usage-service", () => ({ getThisMonthUsage: vi.fn(async () => ({ @@ -147,3 +168,147 @@ describe("LimitService.checkEmailLimit paid-only signups", () => { expect(mockGetTeamCached).not.toHaveBeenCalled(); }); }); + +describe("LimitService.checkEmailLimit new-account limit", () => { + const DAY = 24 * 60 * 60 * 1000; + const NOW = Date.parse("2026-12-20T12:00:00Z"); + const paid = (ageDays: number, overrides: Record = {}) => + team({ + plan: "BASIC", + name: "Acme", + createdAt: new Date(NOW - ageDays * DAY - 60_000).toISOString(), + ...overrides, + }); + // A tiny in-memory stand-in for the Redis reservation script. + let slots: Map>; + + beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(NOW); + mockEnv.NEXT_PUBLIC_IS_CLOUD = true; + mockGetTeamCached.mockReset(); + mockUsageAggregate.mockReset(); + mockEmailTeam.mockReset(); + mockRedisSet.mockReset(); + mockRedisSet.mockResolvedValue("OK"); + mockUsageAggregate.mockResolvedValue({ + _sum: { sent: 0, hardBounced: 0, complained: 0 }, + }); + slots = new Map(); + mockRedisEval.mockReset(); + mockRedisEval.mockImplementation( + async ( + _script: string, + _n: number, + key: string, + id: string, + recipients: string, + limit: string, + ) => { + const claims = slots.get(key) ?? new Map(); + slots.set(key, claims); + if (claims.has(id)) return 1; + const total = [...claims.values()].reduce((a, b) => a + b, 0); + if (total + Number(recipients) > Number(limit)) return 0; + claims.set(id, Number(recipients)); + return 1; + }, + ); + }); + afterEach(() => vi.useRealTimers()); + + it("lets a day-old paid team send 200 emails, then stops it and tells it once", async () => { + mockGetTeamCached.mockResolvedValue(paid(0)); + for (let i = 0; i < 200; i++) { + await expect( + LimitService.checkEmailLimit(1, [], { id: `e${i}`, recipients: 1 }), + ).resolves.toMatchObject({ + isLimitReached: false, + }); + } + // A retry of an email that already has a slot still goes. + await expect( + LimitService.checkEmailLimit(1, [], { id: "e5", recipients: 1 }), + ).resolves.toMatchObject({ + isLimitReached: false, + }); + await expect( + LimitService.checkEmailLimit(1, [], { id: "e200", recipients: 1 }), + ).resolves.toMatchObject({ + isLimitReached: true, + limit: 200, + reason: LimitReason.EMAIL_DAILY_LIMIT_REACHED, + }); + await vi.waitFor(() => + expect(mockEmailTeam).toHaveBeenCalledWith( + 1, + expect.stringContaining("limit for new accounts"), + expect.stringContaining("200"), + ), + ); + + mockRedisSet.mockResolvedValue(null); // already told today + await LimitService.checkEmailLimit(1, [], { id: "e201", recipients: 1 }); + await Promise.resolve(); + expect(mockEmailTeam).toHaveBeenCalledTimes(1); + }); + + it("counts every recipient, so a big bcc can't slip past the limit", async () => { + mockGetTeamCached.mockResolvedValue(paid(0)); + await expect( + LimitService.checkEmailLimit(1, [], { id: "bcc-blast", recipients: 250 }), + ).resolves.toMatchObject({ isLimitReached: true, limit: 200 }); + for (const id of ["a", "b"]) { + await expect( + LimitService.checkEmailLimit(1, [], { id, recipients: 100 }), + ).resolves.toMatchObject({ isLimitReached: false }); + } + await expect( + LimitService.checkEmailLimit(1, [], { id: "c", recipients: 1 }), + ).resolves.toMatchObject({ isLimitReached: true }); + }); + + it("keeps sending if the check itself fails", async () => { + mockGetTeamCached.mockResolvedValue(paid(0)); + mockRedisEval.mockRejectedValue(new Error("redis down")); + await expect( + LimitService.checkEmailLimit(1, [], { id: "e1", recipients: 1 }), + ).resolves.toMatchObject({ + isLimitReached: false, + }); + }); + + it("keeps sending if Redis hangs instead of failing", async () => { + mockGetTeamCached.mockResolvedValue(paid(0)); + mockRedisEval.mockReturnValue(new Promise(() => {})); // never settles + const started = performance.now(); + await expect( + LimitService.checkEmailLimit(1, [], { id: "e1", recipients: 1 }), + ).resolves.toMatchObject({ + isLimitReached: false, + }); + expect(performance.now() - started).toBeLessThan(5_000); + }); + + it("never touches established customers, grandfathered teams or custom limits", async () => { + const before = team({ + plan: "BASIC", + createdAt: "2026-11-27T10:00:00Z", + }); + for (const t of [ + paid(14), + paid(300), + paid(0, { dailyEmailLimit: 50_000 }), + before, + ]) { + mockGetTeamCached.mockResolvedValue(t); + await expect( + LimitService.checkEmailLimit(1, [], { id: "e1", recipients: 1 }), + ).resolves.toMatchObject({ + isLimitReached: false, + }); + } + expect(mockUsageAggregate).not.toHaveBeenCalled(); + expect(mockRedisEval).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/server/service/new-sender-ramp.ts b/apps/web/src/server/service/new-sender-ramp.ts new file mode 100644 index 000000000..2a3a0c0ae --- /dev/null +++ b/apps/web/src/server/service/new-sender-ramp.ts @@ -0,0 +1,67 @@ +// A new team's daily limit starts low and grows over its first two weeks, so a +// bought or scraped list can't be blasted the day an account is paid for. +// Pure, so tests and the limit check share it. +// +// Calibration (Nov 2026): of 31 teams that sent in their first 14 days over a +// year, every lasting customer stayed under 150 emails a day; the only ones +// above were one-off blasts (6,116, 2,952, 2,943 and 780 on day 0-1). + +import { judgeCounts, type SendingCounts } from "./sending-rules"; + +/** The schema default for `Team.dailyEmailLimit`. Any other value was set by an admin. */ +export const DEFAULT_DAILY_EMAIL_LIMIT = 10_000; + +/** Per-day caps by account age (whole days since the team was created). */ +export const NEW_SENDER_RAMP = [ + { beforeDay: 3, perDay: 200 }, + { beforeDay: 7, perDay: 1_000 }, + { beforeDay: 14, perDay: 5_000 }, +] as const; + +const DAY_MS = 24 * 60 * 60 * 1000; + +/** + * Teams created before the ramp shipped keep the limits they signed up with + * (founder: existing customers aren't affected). + */ +export const RAMP_STARTS_AT = Date.parse("2026-11-28T00:00:00Z"); + +/** + * Today's cap for a team still in its first 14 days, or null when the ramp + * doesn't apply: an older team, or one whose daily limit an admin set by hand + * (e.g. a business moving its existing volume over on day one). + * + * A team whose sending so far would trip the bounce/complaint rules stays at + * the first step instead of growing. + */ +export function newSenderDailyLimit( + team: { createdAt?: Date | string | null; dailyEmailLimit: number }, + counts: SendingCounts, + now = Date.now(), +): number | null { + if (!team.createdAt) return null; + if (team.dailyEmailLimit !== DEFAULT_DAILY_EMAIL_LIMIT) return null; + const created = new Date(team.createdAt).getTime(); + if (Number.isNaN(created) || created < RAMP_STARTS_AT) return null; + const ageDays = Math.floor((now - created) / DAY_MS); + const step = NEW_SENDER_RAMP.find((s) => ageDays < s.beforeDay); + if (!step) return null; + if (judgeCounts(counts).level !== "ok") return NEW_SENDER_RAMP[0].perDay; + return step.perDay; +} + +/** The email a team gets (once a day) when an email is refused by its new-account limit. */ +export function newSenderLimitEmail(input: { + teamName: string; + limit: number; + settingsUrl: string; +}) { + const steps = NEW_SENDER_RAMP.map( + (s, i) => + `- ${i === 0 ? "first 3 days" : `until day ${s.beforeDay}`}: ${s.perDay.toLocaleString()} emails a day`, + ).join("\n"); + return { + subject: "useSend: an email went over today's limit for new accounts", + text: `Hi ${input.teamName} team,\n\nNew accounts can email up to ${input.limit.toLocaleString()} recipients a day (each to, cc and bcc address counts as one). An email that would go over today's limit isn't sent: it fails instead. Smaller emails can still go out while there's room, and the limit resets at midnight UTC.\n\nNew accounts start lower and grow automatically over the first two weeks, as long as bounces and spam complaints stay low:\n${steps}\n- after that: your plan's full daily limit\n\nIf you're moving existing sending to useSend and need more from day one, reply to this email and tell us about it.\n\n${input.settingsUrl}\n\nuseSend`, + }; +} diff --git a/apps/web/src/server/service/new-sender-ramp.unit.test.ts b/apps/web/src/server/service/new-sender-ramp.unit.test.ts new file mode 100644 index 000000000..186e9fe67 --- /dev/null +++ b/apps/web/src/server/service/new-sender-ramp.unit.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from "vitest"; + +import { + DEFAULT_DAILY_EMAIL_LIMIT, + newSenderDailyLimit, + newSenderLimitEmail, +} from "~/server/service/new-sender-ramp"; + +const DAY = 24 * 60 * 60 * 1000; +const now = Date.parse("2026-12-20T12:00:00Z"); +const clean = { sent: 0, hardBounced: 0, complained: 0 }; +const team = ( + ageDays: number, + dailyEmailLimit = DEFAULT_DAILY_EMAIL_LIMIT, +) => ({ + createdAt: new Date(now - ageDays * DAY - 60_000), + dailyEmailLimit, +}); + +describe("newSenderDailyLimit", () => { + it("starts at 200 a day and grows over the first two weeks", () => { + expect(newSenderDailyLimit(team(0), clean, now)).toBe(200); + expect(newSenderDailyLimit(team(2), clean, now)).toBe(200); + expect(newSenderDailyLimit(team(3), clean, now)).toBe(1_000); + expect(newSenderDailyLimit(team(6), clean, now)).toBe(1_000); + expect(newSenderDailyLimit(team(7), clean, now)).toBe(5_000); + expect(newSenderDailyLimit(team(13), clean, now)).toBe(5_000); + }); + + it("never applies to established teams", () => { + expect(newSenderDailyLimit(team(14), clean, now)).toBeNull(); + expect(newSenderDailyLimit(team(400), clean, now)).toBeNull(); + }); + + it("never applies to teams created before it shipped (existing customers)", () => { + const created = Date.parse("2026-11-27T23:00:00Z"); + expect( + newSenderDailyLimit( + { + createdAt: new Date(created), + dailyEmailLimit: DEFAULT_DAILY_EMAIL_LIMIT, + }, + clean, + created + DAY, + ), + ).toBeNull(); + }); + + it("skips teams whose limit an admin set by hand", () => { + expect(newSenderDailyLimit(team(0, 50_000), clean, now)).toBeNull(); + expect(newSenderDailyLimit(team(0, 500), clean, now)).toBeNull(); + }); + + it("skips a team without a creation date (e.g. an old cache entry)", () => { + expect( + newSenderDailyLimit( + { dailyEmailLimit: DEFAULT_DAILY_EMAIL_LIMIT }, + clean, + now, + ), + ).toBeNull(); + }); + + it("doesn't grow while bounces or complaints are high", () => { + const complaints = { sent: 600, hardBounced: 0, complained: 3 }; + const bounces = { sent: 600, hardBounced: 30, complained: 0 }; + expect(newSenderDailyLimit(team(8), complaints, now)).toBe(200); + expect(newSenderDailyLimit(team(4), bounces, now)).toBe(200); + // A single complaint doesn't hold it back. + expect( + newSenderDailyLimit( + team(8), + { sent: 600, hardBounced: 1, complained: 1 }, + now, + ), + ).toBe(5_000); + }); +}); + +describe("newSenderLimitEmail", () => { + it("explains the limit, the schedule and how to ask for more", () => { + const { subject, text } = newSenderLimitEmail({ + teamName: "Acme", + limit: 200, + settingsUrl: "https://app.usesend.com/settings", + }); + expect(subject).toContain("limit for new accounts"); + expect(text).toContain("up to 200 recipients a day"); + // It never claims the team sent the whole cap (one big email may be all that was refused). + expect(text).not.toMatch(/You've sent/); + expect(text).toContain("first 3 days: 200 emails a day"); + expect(text).toContain("until day 7: 1,000 emails a day"); + expect(text).toContain("until day 14: 5,000 emails a day"); + expect(text).toContain("reply to this email"); + }); +}); diff --git a/apps/web/src/server/utils/from-address.ts b/apps/web/src/server/utils/from-address.ts index 1df1deefe..eb330f996 100644 --- a/apps/web/src/server/utils/from-address.ts +++ b/apps/web/src/server/utils/from-address.ts @@ -30,3 +30,24 @@ export function parseFromAddress(from: string): ParsedFromAddress | undefined { return { name: entry.name, address: entry.address, domain }; } + +/** + * How many mailboxes a list of to/cc/bcc entries reaches, parsed the way + * Nodemailer does when it sends (one entry can hold "a@x.com, b@x.com"; a + * quoted display name with a comma is still one mailbox; groups are expanded). + */ +export function countMailboxes( + entries: Array, +): number { + let count = 0; + for (const entry of entries) { + if (!entry) continue; + for (const parsed of addressparser(entry)) { + const group = (parsed as { group?: Array<{ address?: string }> }).group; + if (Array.isArray(group)) + count += group.filter((member) => member.address).length; + else if (parsed.address) count += 1; + } + } + return count; +} diff --git a/apps/web/src/server/utils/from-address.unit.test.ts b/apps/web/src/server/utils/from-address.unit.test.ts index 998837fc6..393ba8246 100644 --- a/apps/web/src/server/utils/from-address.unit.test.ts +++ b/apps/web/src/server/utils/from-address.unit.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import nodemailer from "nodemailer"; import addressparser from "nodemailer/lib/addressparser"; -import { parseFromAddress } from "~/server/utils/from-address"; +import { countMailboxes, parseFromAddress } from "~/server/utils/from-address"; async function emittedFromAddress(from: { name: string; address: string }) { const { message } = await nodemailer @@ -73,3 +73,17 @@ describe("parseFromAddress", () => { expect(await emittedFromAddress(parsed!)).toBe(parsed!.address); }); }); + +describe("countMailboxes", () => { + it("counts mailboxes the way Nodemailer sends them", () => { + expect(countMailboxes(["a@example.com"])).toBe(1); + expect( + countMailboxes(["a@example.com, b@example.com", "c@example.com"]), + ).toBe(3); + // A quoted display name with a comma is one mailbox. + expect(countMailboxes(['"Name, User" '])).toBe(1); + // Groups expand to their members. + expect(countMailboxes(["Team: a@example.com, b@example.com;"])).toBe(2); + expect(countMailboxes([])).toBe(0); + }); +});