Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
Send app email over SMTP; drop Resend as the transport (#1652)
Sid9fe6981ea8ef
diff --git a/.claude/rules/environment-configuration.md b/.claude/rules/environment-configuration.mdindex dd98afa175..cb97e44c88 100644--- a/.claude/rules/environment-configuration.md+++ b/.claude/rules/environment-configuration.md@@ -82,8 +82,11 @@ process.env before invoking compose so these survive a recreate; see theendpoint (`/api/webhook/stripe`, billing) and the Connect endpoint(`/api/webhook/stripe-connect`, connected-account events) are signed separately.-**Email** — `RESEND_API_KEY`, `RESEND_DOMAIN` (default `carbon.ms`),-`DISABLE_RESEND` (short-circuits sends), optional `RESEND_AUDIENCE_ID`.+**Email** — `SMTP_HOST`, `SMTP_PORT` (465 = implicit TLS, 587 = STARTTLS,+default 587), `SMTP_USER`, `SMTP_PASSWORD`, `SMTP_FROM` (default+`Carbon <[email protected]>`). All optional — unset disables email sending.+Optional `RESEND_API_KEY` (marketing contacts; also a legacy SMTP fallback via+smtp.resend.com when `SMTP_*` is unset) and `RESEND_AUDIENCE_ID`.**Integrations (all optional)** — Slack (`SLACK_BOT_TOKEN`, `SLACK_CLIENT_ID`,`SLACK_CLIENT_SECRET`, `SLACK_SIGNING_SECRET`, `SLACK_STATE_SECRET`,@@ -114,9 +117,9 @@ set to `production` in prod compose), `VERCEL_ENV`, `NODE_ENV`. `ERP_URL` /- Required-var validation runs at **module load** — a missing `SUPABASE_URL`,`SUPABASE_SERVICE_ROLE_KEY`, `SUPABASE_DB_URL`, `REDIS_URL`, `SESSION_SECRET`,`POSTHOG_*`, or `VERCEL_URL` crashes boot, not lazily at first use.-- `packages/lib/src/resend.server.ts` does `new Resend(process.env.RESEND_API_KEY!)`- at module load, so ERP needs a non-empty `RESEND_API_KEY` to boot even if you- don't send email (use any placeholder, e.g. `re_placeholder`).+- Email is deliberately lazy: `packages/lib/src/email.server.ts` builds the+ SMTP transport on first send, never at import, so a deployment with no mail+ config boots fine and `sendEmail` no-ops.- Only keys in `getBrowserEnv()` reach the client; adding a public var meansadding it there AND to the `Window.env` interface declaration.- Don't put ports/URLs/Supabase/Redis/Inngest dev values in `.env` — `crbn up`diff --git a/.claude/rules/project-overview.md b/.claude/rules/project-overview.mdindex c524cfab4d..692810875a 100644--- a/.claude/rules/project-overview.md+++ b/.claude/rules/project-overview.md@@ -29,7 +29,7 @@ pnpm + Turborepo monorepo of `apps/*` and `packages/*`.types, and a typed Kysely client.- **jobs** — Inngest-powered background job orchestration (events, email/PDFrendering, printing, webhooks). `inngest-cli dev` for local.-- **lib** — Shared backend utilities: Inngest client, Resend email, Slack helpers,+- **lib** — Shared backend utilities: Inngest client, SMTP email, Slack helpers,event definitions.- **react** — Shared UI component library (Radix UI, TanStack Table/Virtual,Recharts, rich-text/editor). Grep here before writing UI.diff --git a/.env.example b/.env.exampleindex 5f85fb123b..ff61199744 100644--- a/.env.example+++ b/.env.example@@ -31,9 +31,16 @@ STRIPE_CONNECT_WEBHOOK_SECRET="whsec_************"# GTM (notifications fan-out)GTM_EVENTS_API_SECRET_KEY=""-# Resend-RESEND_API_KEY="************************"-RESEND_DOMAIN="carbon.ms"+# SMTP (email transport; leave unset to disable email)+# Port 465 = implicit TLS, 587 = STARTTLS+SMTP_HOST=""+SMTP_PORT="587"+SMTP_USER=""+SMTP_PASSWORD="************************"+SMTP_FROM="Carbon <[email protected]>"++# Resend (marketing contacts only — optional; also a legacy SMTP fallback when SMTP_* is unset)+# RESEND_API_KEY="************************"# RESEND_AUDIENCE_ID="*****" # Optional — required for contact management in `packages/jobs`# Inngest (production keys; dev mode flags are in .env.local)diff --git a/README.md b/README.mdindex f2eb9ea645..7f6da4a0da 100644--- a/README.md+++ b/README.md@@ -118,7 +118,7 @@ Carbon is designed to make it easy for you to extend the platform by building yo| Auth | [Supabase](https://supabase.com) || Cache | [Redis](https://redis.io) || Jobs | [Inngest](https://inngest.com) |-| Email | [Resend](https://resend.com) |+| Email | SMTP ([Nodemailer](https://nodemailer.com)) || i18n | [Lingui](https://lingui.dev) || Hosting | [Vercel](https://vercel.com) || Billing | [Stripe](https://stripe.com) |@@ -180,7 +180,7 @@ You'll also want accounts with the following external services:| ---------------------------------------------------- | -------------------------- || [Posthog](https://us.posthog.com/signup) | Product analytics platform || [Stripe](https://dashboard.stripe.com/login) | Payments service |-| [Resend](https://resend.com) | Email service |+| An SMTP provider (e.g. [Resend](https://resend.com)) | Email service |Posthog has a free tier which should be plenty to support local development. If you're self hosting and you don't want to use Posthog, it's pretty easy to remove the analytics.@@ -296,7 +296,7 @@ Then configure each service:Signing in requires you to set up one of two methods:-- Email requires a Resend API key (you'll set this up later on)+- Email requires SMTP credentials (you'll set this up later on)- Sign-in with Google requires a Google auth client with these variables. [See the Supabase docs for instructions on how to set this up](https://supabase.com/docs/guides/auth/social-login/auth-google):- Set `Authorized JavaScript origins` to `https://api.carbon.dev`- Set `Authorized redirect URIs` to `https://api.carbon.dev/auth/v1/callback`@@ -316,7 +316,7 @@ Backend services run inside the per-worktree docker stack — `crbn up` boots th- `SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_ROLE_KEY` — keys minted per-worktree from a random `SUPABASE_JWT_SECRET`- `SUPABASE_DB_URL` — direct Postgres URL on a dynamic port-`.env.local` is generated; do not commit it or hand-edit values that came from `crbn up` (they are re-derived on each boot). Put genuine secrets (OAuth client IDs, Stripe keys, Resend) in `.env` only.+`.env.local` is generated; do not commit it or hand-edit values that came from `crbn up` (they are re-derived on each boot). Put genuine secrets (OAuth client IDs, Stripe keys, SMTP credentials) in `.env` only.Run `crbn status` at any time to see the live port assignment and the URLs portless is serving.@@ -349,15 +349,20 @@ In Posthog go to `https://[region].posthog.com/project/[project-id]/settings/pro</details><details>-<summary><strong>6. Resend (email)</strong></summary>+<summary><strong>6. SMTP (email)</strong></summary>-[Create a Resend account](https://resend.com) and configure:+Transactional email (user invitations, email verification, onboarding) is sent over SMTP. Any provider works — Resend, Amazon SES, or your own relay:-- `RESEND_API_KEY="re_**********"`-- `RESEND_DOMAIN="carbon.ms"` (or your domain, no trailing slashes or protocols)-- `RESEND_AUDIENCE_ID="*****"` (Optional — required for contact management in `packages/jobs`)+- `SMTP_HOST="smtp.example.com"`+- `SMTP_PORT="587"` (465 uses implicit TLS, 587 uses STARTTLS)+- `SMTP_USER="********"`+- `SMTP_PASSWORD="********"`+- `SMTP_FROM="Carbon <[email protected]>"`++Leave them unset to disable email entirely — the apps boot and run fine without it.-Resend is used for transactional emails (user invitations, email verification, onboarding). All three variables are stored in `packages/auth/src/config/env.ts`.+- `RESEND_API_KEY="re_**********"` (Optional — Resend marketing contacts; also a legacy SMTP fallback when `SMTP_*` is unset)+- `RESEND_AUDIENCE_ID="*****"` (Optional — required for contact management in `packages/jobs`)</details>@@ -397,7 +402,7 @@ For local development you don't need email or OAuth configured. `crbn up` seedsYou'll land on the authenticated dashboard (`/x`) — no inbox check required. The same session cookie works for the MES app at `https://<worktree>.mes.dev`.-> The bypass only applies to the exact address in `DEV_BYPASS_EMAIL` and only when that user is active — it's a dev convenience, not present in production. Any other email falls back to the normal magic-link / verification flow (which needs Resend configured). To sign in as your own account instead, use the magic link and read it from the local mail catcher at `https://<worktree>.mail.dev`.+> The bypass only applies to the exact address in `DEV_BYPASS_EMAIL` and only when that user is active — it's a dev convenience, not present in production. Any other email falls back to the normal magic-link / verification flow (which needs SMTP configured). To sign in as your own account instead, use the magic link and read it from the local mail catcher at `https://<worktree>.mail.dev`.<br />diff --git a/apps/erp/app/modules/agent/kb/docs/platform/self-hosting/environment-variables.md b/apps/erp/app/modules/agent/kb/docs/platform/self-hosting/environment-variables.mdindex afb544f977..2f27d616c7 100644--- a/apps/erp/app/modules/agent/kb/docs/platform/self-hosting/environment-variables.md+++ b/apps/erp/app/modules/agent/kb/docs/platform/self-hosting/environment-variables.md@@ -58,8 +58,12 @@ Override the Inngest endpoint (self-hosted or dev).## Email & billing-Resend API key for transactional email.-Verified sending domain.+SMTP server for transactional email. Unset disables email sending.+SMTP port; 465 uses implicit TLS, 587 (default) uses STARTTLS.+SMTP username.+SMTP password.+From-address for outgoing email, e.g. `Carbon <[email protected]>`.+Optional. Resend marketing-contacts API; also a legacy SMTP fallback when `SMTP_*` is unset.Stripe secret key, Cloud / Enterprise billing.Verifies inbound Stripe webhooks.Verifies inbound Stripe Connect webhooks (connected-account events, signed with a separate secret).diff --git a/apps/erp/app/routes/_public+/invite.$code.tsx b/apps/erp/app/routes/_public+/invite.$code.tsxindex 29c40c1f3b..8459ec9066 100644--- a/apps/erp/app/routes/_public+/invite.$code.tsx+++ b/apps/erp/app/routes/_public+/invite.$code.tsx@@ -4,7 +4,6 @@ import {error,getAppUrl,getPermissionCacheKey,- RESEND_DOMAIN,success as successFlash} from "@carbon/auth";import { getCarbonServiceRole } from "@carbon/auth/client.server";@@ -17,7 +16,7 @@ import {import { insertAuditLogEntries } from "@carbon/database/audit";import { InviteEmail } from "@carbon/documents/email";import { Ratelimit, redis } from "@carbon/kv";-import { sendEmail } from "@carbon/lib/resend.server";+import { sendEmail } from "@carbon/lib/email.server";import { getLogger } from "@carbon/logger";import { Button as _Button, Heading as _Heading, VStack } from "@carbon/react";import { updateSubscriptionQuantityForCompany } from "@carbon/stripe/stripe.server";@@ -255,7 +254,6 @@ async function requestNewInvite(.single();await sendEmail({- from: `Carbon <no-reply@${RESEND_DOMAIN}>`,to: invite.data.email,subject: `You have been invited to join ${invite.data.company?.name} on Carbon`,headers: { "X-Entity-Ref-ID": nanoid() },diff --git a/apps/erp/app/routes/x+/users+/customers.new.tsx b/apps/erp/app/routes/x+/users+/customers.new.tsxindex 19435a5114..647053e612 100644--- a/apps/erp/app/routes/x+/users+/customers.new.tsx+++ b/apps/erp/app/routes/x+/users+/customers.new.tsx@@ -2,7 +2,6 @@ import {assertIsPost,CONTROLLED_ENVIRONMENT,error,- RESEND_DOMAIN,success} from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";@@ -11,7 +10,7 @@ import { flash } from "@carbon/auth/session.server";import { InviteEmail } from "@carbon/documents/email";import { getSsoAwareInviteLink } from "@carbon/ee/sso.server";import { validationError, validator } from "@carbon/form";-import { sendEmail } from "@carbon/lib/resend.server";+import { sendEmail } from "@carbon/lib/email.server";import { getLogger } from "@carbon/logger";import { render } from "@react-email/components";import { nanoid } from "nanoid";@@ -87,7 +86,6 @@ export async function action({ request }: ActionFunctionArgs) {);await sendEmail({- from: `Carbon <no-reply@${RESEND_DOMAIN}>`,to: result.email,subject: `You have been invited to join ${company.data?.name} on Carbon`,headers: {diff --git a/apps/erp/app/routes/x+/users+/employees.new.tsx b/apps/erp/app/routes/x+/users+/employees.new.tsxindex 8a95a1f5d4..55077724b0 100644--- a/apps/erp/app/routes/x+/users+/employees.new.tsx+++ b/apps/erp/app/routes/x+/users+/employees.new.tsx@@ -2,7 +2,6 @@ import {assertIsPost,CONTROLLED_ENVIRONMENT,error,- RESEND_DOMAIN,success} from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";@@ -11,7 +10,7 @@ import { flash } from "@carbon/auth/session.server";import { InviteEmail } from "@carbon/documents/email";import { getSsoAwareInviteLink } from "@carbon/ee/sso.server";import { validationError, validator } from "@carbon/form";-import { sendEmail } from "@carbon/lib/resend.server";+import { sendEmail } from "@carbon/lib/email.server";import { getLogger } from "@carbon/logger";import { datetime } from "@carbon/utils";import { render } from "@react-email/components";@@ -146,7 +145,6 @@ export async function action({ request }: ActionFunctionArgs) {);await sendEmail({- from: `Carbon <no-reply@${RESEND_DOMAIN}>`,to: email,subject: `You have been invited to join ${company.data?.name} on Carbon`,headers: {diff --git a/apps/erp/app/routes/x+/users+/resend-invite.tsx b/apps/erp/app/routes/x+/users+/resend-invite.tsxindex 6008d685d8..fa11e4c719 100644--- a/apps/erp/app/routes/x+/users+/resend-invite.tsx+++ b/apps/erp/app/routes/x+/users+/resend-invite.tsx@@ -1,9 +1,4 @@-import {- CONTROLLED_ENVIRONMENT,- error,- RESEND_DOMAIN,- success-} from "@carbon/auth";+import { CONTROLLED_ENVIRONMENT, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";@@ -11,7 +6,7 @@ import { InviteEmail } from "@carbon/documents/email";import { getSsoAwareInviteLink } from "@carbon/ee/sso.server";import { validationError, validator } from "@carbon/form";import { batchTrigger } from "@carbon/jobs";-import { sendEmail } from "@carbon/lib/resend.server";+import { sendEmail } from "@carbon/lib/email.server";import { datetime } from "@carbon/utils";import { render } from "@react-email/components";import { nanoid } from "nanoid";@@ -106,7 +101,6 @@ export async function action({ request }: ActionFunctionArgs) {);await sendEmail({- from: `Carbon <no-reply@${RESEND_DOMAIN}>`,to: user.data.email,subject: `You have been invited to join ${company.data?.name} on Carbon`,headers: {diff --git a/apps/erp/app/routes/x+/users+/suppliers.new.tsx b/apps/erp/app/routes/x+/users+/suppliers.new.tsxindex 55c689d1a6..a6ddc10992 100644--- a/apps/erp/app/routes/x+/users+/suppliers.new.tsx+++ b/apps/erp/app/routes/x+/users+/suppliers.new.tsx@@ -2,7 +2,6 @@ import {assertIsPost,CONTROLLED_ENVIRONMENT,error,- RESEND_DOMAIN,success} from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";@@ -11,7 +10,7 @@ import { flash } from "@carbon/auth/session.server";import { InviteEmail } from "@carbon/documents/email";import { getSsoAwareInviteLink } from "@carbon/ee/sso.server";import { validationError, validator } from "@carbon/form";-import { sendEmail } from "@carbon/lib/resend.server";+import { sendEmail } from "@carbon/lib/email.server";import { getLogger } from "@carbon/logger";import { render } from "@react-email/components";import { nanoid } from "nanoid";@@ -87,7 +86,6 @@ export async function action({ request }: ActionFunctionArgs) {);await sendEmail({- from: `Carbon <no-reply@${RESEND_DOMAIN}>`,to: result.email,subject: `You have been invited to join ${company.data?.name} on Carbon`,headers: {diff --git a/contrib/deploying/simple-docker-caddy/.env.example b/contrib/deploying/simple-docker-caddy/.env.exampleindex ddfd6b1525..88343bb662 100644--- a/contrib/deploying/simple-docker-caddy/.env.example+++ b/contrib/deploying/simple-docker-caddy/.env.example@@ -32,7 +32,9 @@ [email protected]# ── App config ───────────────────────────────────────────────────────────────CARBON_EDITION=community-RESEND_DOMAIN=example.com+# From-address for app email (envelope sender). The apps share the GOTRUE_SMTP_*+# host/port/user below and the `smtp_password` Docker secret.+SMTP_FROM="Carbon <[email protected]>"# ── Container images ─────────────────────────────────────────────────────────# Default: build locally on the VPS (`deploy.sh build`) tagging carbon/<app>:latest.diff --git a/contrib/deploying/simple-docker-caddy/deploy.sh b/contrib/deploying/simple-docker-caddy/deploy.shindex 92fae20717..696f4609e2 100755--- a/contrib/deploying/simple-docker-caddy/deploy.sh+++ b/contrib/deploying/simple-docker-caddy/deploy.sh@@ -127,11 +127,15 @@ cmd_init() {fi# Operator-supplied secrets — placeholders so the stack deploys; replace later.- # ERP crashes on boot with an empty RESEND_API_KEY, so seed a non-empty value.+ # resend_api_key is optional (marketing contacts / legacy fallback); app email+ # sends over SMTP using the shared GOTRUE_SMTP_* config + smtp_password.for s in $SUPPLIED_SECRETS; dosecret_exists "$s" && continuecase "$s" in- resend_api_key) create_secret "$s" "re_placeholder_change_me" ;;+ # Seeded EMPTY on purpose: a truthy placeholder would engage the+ # legacy Resend SMTP fallback with junk credentials instead of+ # letting email no-op.+ resend_api_key) create_secret "$s" "" ;;smtp_password) create_secret "$s" "change_me" ;;# Ignored while SAML_ENABLED=false; replace before enabling SAML.saml_private_key) create_secret "$s" "change_me" ;;@@ -141,7 +145,7 @@ cmd_init() {log "Secrets ready."warn "Next:"warn " 1. Edit $ENV_FILE — set CARBON_REPO, the *_HOST/*_URL, ACME_EMAIL, SMTP."- warn " 2. Set real secrets: $SCRIPT_NAME secret resend_api_key re_xxx (then smtp_password)"+ warn " 2. Set real secrets: $SCRIPT_NAME secret smtp_password xxx (resend_api_key is optional)"warn " 3. $SCRIPT_NAME up"}diff --git a/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml b/contrib/deploying/simple-docker-caddy/docker-compose.prod.ymlindex 1dee0e0e59..436d853fa7 100644--- a/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml+++ b/contrib/deploying/simple-docker-caddy/docker-compose.prod.yml@@ -61,6 +61,7 @@ services:- inngest_signing_key- inngest_event_key- resend_api_key+ - smtp_passwordenvironment:NODE_ENV: productionPORT: "3000"@@ -80,7 +81,11 @@ services:INNGEST_SIGNING_KEY: __INNGEST_SIGNING_KEY__INNGEST_EVENT_KEY: __INNGEST_EVENT_KEY__RESEND_API_KEY: __RESEND_API_KEY__- RESEND_DOMAIN: ${RESEND_DOMAIN:-}+ SMTP_HOST: ${GOTRUE_SMTP_HOST:-}+ SMTP_PORT: ${GOTRUE_SMTP_PORT:-587}+ SMTP_USER: ${GOTRUE_SMTP_USER:-}+ SMTP_PASSWORD: __SMTP_PASSWORD__+ SMTP_FROM: ${SMTP_FROM:-}volumes:- *shimhealthcheck:diff --git a/docs/content/docs/platform/self-hosting/environment-variables.mdx b/docs/content/docs/platform/self-hosting/environment-variables.mdxindex a0c95b0af6..843812a5a7 100644--- a/docs/content/docs/platform/self-hosting/environment-variables.mdx+++ b/docs/content/docs/platform/self-hosting/environment-variables.mdx@@ -72,8 +72,12 @@ Sign-in bot protection uses Cloudflare Turnstile: `CLOUDFLARE_TURNSTILE_SITE_KEY## Email & billing<EnvVars>-<EnvVar name="RESEND_API_KEY" type="string">Resend API key for transactional email.</EnvVar>-<EnvVar name="RESEND_DOMAIN" type="string">Verified sending domain.</EnvVar>+<EnvVar name="SMTP_HOST" type="string">SMTP server for transactional email. Unset disables email sending.</EnvVar>+<EnvVar name="SMTP_PORT" type="number">SMTP port; 465 uses implicit TLS, 587 (default) uses STARTTLS.</EnvVar>+<EnvVar name="SMTP_USER" type="string">SMTP username.</EnvVar>+<EnvVar name="SMTP_PASSWORD" type="string">SMTP password.</EnvVar>+<EnvVar name="SMTP_FROM" type="string">From-address for outgoing email, e.g. `Carbon <[email protected]>`.</EnvVar>+<EnvVar name="RESEND_API_KEY" type="string">Optional. Resend marketing-contacts API; also a legacy SMTP fallback when `SMTP_*` is unset.</EnvVar><EnvVar name="STRIPE_SECRET_KEY" type="string">Stripe secret key, Cloud / Enterprise billing.</EnvVar><EnvVar name="STRIPE_WEBHOOK_SECRET" type="string">Verifies inbound Stripe webhooks.</EnvVar><EnvVar name="STRIPE_CONNECT_WEBHOOK_SECRET" type="string">Verifies inbound Stripe Connect webhooks (connected-account events, signed with a separate secret).</EnvVar>diff --git a/packages/auth/src/services/api-key-cache.test.ts b/packages/auth/src/services/api-key-cache.test.tsindex 3adcaefc7b..d3799447c9 100644--- a/packages/auth/src/services/api-key-cache.test.ts+++ b/packages/auth/src/services/api-key-cache.test.ts@@ -15,7 +15,6 @@ vi.mock("@carbon/kv", () => ({// Env is validated at import time (getEnv throws on missing required vars), so we// stub the config module rather than requiring a full environment in the test run.vi.mock("../config/env", () => ({- RESEND_DOMAIN: "test.dev",DOMAIN: "localhost",ERP_URL: "http://localhost:3000",MES_URL: "http://localhost:3001",diff --git a/packages/auth/src/services/auth-redis-resilience.test.ts b/packages/auth/src/services/auth-redis-resilience.test.tsindex 257504dae8..83db31a90a 100644--- a/packages/auth/src/services/auth-redis-resilience.test.ts+++ b/packages/auth/src/services/auth-redis-resilience.test.ts@@ -17,7 +17,6 @@ vi.mock("@carbon/kv", () => ({// Env is validated at import time (getEnv throws on missing required vars), so we// stub the config module rather than requiring a full environment in the test run.vi.mock("../config/env", () => ({- RESEND_DOMAIN: "test.dev",DOMAIN: "localhost",ERP_URL: "http://localhost:3000",MES_URL: "http://localhost:3001",@@ -30,7 +29,7 @@ vi.mock("../config/env", () => ({}));// Heavy / side-effectful dependencies of the modules under test.-vi.mock("@carbon/lib/resend.server", () => ({+vi.mock("@carbon/lib/email.server", () => ({sendEmail: vi.fn().mockResolvedValue({ error: null })}));vi.mock("@carbon/documents/email", () => ({@@ -75,7 +74,7 @@ vi.mock("./mfa.server", () => ({}));import { redis } from "@carbon/kv";-import { sendEmail } from "@carbon/lib/resend.server";+import { sendEmail } from "@carbon/lib/email.server";import type { AuthSession } from "../types";import {getAndDeleteAuthChallenge,diff --git a/packages/auth/src/services/verification.server.ts b/packages/auth/src/services/verification.server.tsindex f8e9d6b7f9..a956e25f80 100644--- a/packages/auth/src/services/verification.server.ts+++ b/packages/auth/src/services/verification.server.ts@@ -1,9 +1,8 @@import { VerificationEmail } from "@carbon/documents/email";import { redis } from "@carbon/kv";-import { sendEmail } from "@carbon/lib/resend.server";+import { sendEmail } from "@carbon/lib/email.server";import { getLogger } from "@carbon/logger";import { render } from "@react-email/components";-import { RESEND_DOMAIN } from "../config/env";const log = getLogger("auth");@@ -39,14 +38,15 @@ export async function sendVerificationCode(email: string) {);const result = await sendEmail({- from: `Carbon <no-reply@${RESEND_DOMAIN}>`,to: email,subject: "Verify your email address",html});log.debug("Verification email sent", { result });- return !result.error;+ // `data: null` with no error is the SMTP-unconfigured no-op — the user+ // will never receive a code, so don't report success.+ return !result.error && result.data !== null;} catch (error) {log.error("Failed to send verification code", { error });return false;diff --git a/packages/env/AGENTS.md b/packages/env/AGENTS.mdindex 1412dc06f6..fb3b9db16d 100644--- a/packages/env/AGENTS.md+++ b/packages/env/AGENTS.md@@ -37,7 +37,7 @@ All from `src/index.ts` (single file):- **Edition:** `CarbonEdition` (Community/Cloud/Enterprise/Test), `CONTROLLED_ENVIRONMENT` (ITAR flag)- **URLs:** `getAppUrl()`, `getMESUrl()`, `getBrowserEnv()`- **Logging:** `LOG_LEVEL` (optional, non-secret, browser-safe — consumed by `@carbon/logger`)-- **Integrations:** Stripe, Resend, Slack, Xero, Jira, OnShape, QuickBooks keys (all optional)+- **Integrations:** Stripe, SMTP email, Slack, Xero, Jira, OnShape, QuickBooks keys (all optional)## Cross-Referencesdiff --git a/packages/env/src/index.ts b/packages/env/src/index.tsindex 4ccfdba4f9..3e5e294772 100644--- a/packages/env/src/index.ts+++ b/packages/env/src/index.ts@@ -54,7 +54,6 @@ declare global {QUICKBOOKS_ENVIRONMENT: string;QUICKBOOKS_WEBHOOK_SECRET: string;RESEND_API_KEY: string;- RESEND_DOMAIN: string;SESSION_SECRET: string;SESSION_KEY: string;SESSION_ERROR_KEY: string;@@ -63,6 +62,11 @@ declare global {SLACK_OAUTH_REDIRECT_URL: string;SLACK_SIGNING_SECRET: string;SLACK_STATE_SECRET: string;+ SMTP_FROM: string;+ SMTP_HOST: string;+ SMTP_PASSWORD: string;+ SMTP_PORT: string;+ SMTP_USER: string;STRIPE_SECRET_KEY: string;STRIPE_WEBHOOK_SECRET: string;STRIPE_CONNECT_WEBHOOK_SECRET: string;@@ -290,10 +294,24 @@ export const QUICKBOOKS_WEBHOOK_SECRET = getEnv("QUICKBOOKS_WEBHOOK_SECRET", {isSecret: true});-export const RESEND_DOMAIN =- getEnv("RESEND_DOMAIN", {+export const SMTP_FROM = getEnv("SMTP_FROM", {+ isRequired: false+});+export const SMTP_HOST = getEnv("SMTP_HOST", {+ isRequired: false+});+export const SMTP_PASSWORD = getEnv("SMTP_PASSWORD", {+ isRequired: false,+ isSecret: true+});+export const SMTP_PORT = Number(+ getEnv("SMTP_PORT", {isRequired: false- }) ?? "carbon.ms";+ }) || 587+);+export const SMTP_USER = getEnv("SMTP_USER", {+ isRequired: false+});export const SLACK_BOT_TOKEN = getEnv("SLACK_BOT_TOKEN", {isRequired: falsediff --git a/packages/jobs/package.json b/packages/jobs/package.jsonindex 6ee6dc6538..f41566383a 100644--- a/packages/jobs/package.json+++ b/packages/jobs/package.json@@ -26,12 +26,10 @@"inngest": "^3.52.7","kysely": "catalog:","nanoid": "catalog:",- "nodemailer": "9.0.1","pdfjs-dist": "5.4.296","react": "catalog:","react-dom": "catalog:","react-pdf": "catalog:",- "resend": "3.5.0","sst": "catalog:","supabase": "catalog:","tsup": "catalog:",@@ -40,7 +38,6 @@},"devDependencies": {"@carbon/config": "workspace:*",- "@types/nodemailer": "6.4.23","@types/pg": "8.15.6","@types/react": "catalog:","pg": "8.20.0",diff --git a/packages/jobs/src/inngest/functions/notifications/send-email.ts b/packages/jobs/src/inngest/functions/notifications/send-email.tsindex 193591dda7..3890cbc32a 100644--- a/packages/jobs/src/inngest/functions/notifications/send-email.ts+++ b/packages/jobs/src/inngest/functions/notifications/send-email.ts@@ -1,7 +1,6 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";-import { RESEND_DOMAIN } from "@carbon/env";-import { NonRetriableError, serializeError } from "inngest";-import { Resend } from "resend";+import { sendEmail } from "@carbon/lib/email.server";+import { NonRetriableError } from "inngest";import { inngest } from "../../client";export const sendEmailFunction = inngest.createFunction(@@ -13,7 +12,7 @@ export const sendEmailFunction = inngest.createFunction(async ({ event, step, logger }) => {const payload = event.data;- // Resend rejects the request if `to` or `cc` contain null/undefined+ // The mail transport rejects `to` or `cc` lists containing null/undefined// entries, so strip falsy values regardless of what callers pass.const sanitizeRecipients = (value: string | string[] | undefined@@ -37,43 +36,34 @@ export const sendEmailFunction = inngest.createFunction();}- const fromAddress = `Carbon <no-reply@${RESEND_DOMAIN}>`;-const result = await step.run("send-email", async () => {- if (process.env.DISABLE_RESEND) {- logger.info("Resend disabled — skipping send", { toRecipients });- return null;- }-- const resend = new Resend(process.env.RESEND_API_KEY!);-- const email = {+ logger.info("Email Job");+ const response = await sendEmail({attachments: payload.attachments,cc: ccRecipients,- from: fromAddress,html: payload.html,- reply_to: payload.from,+ replyTo: payload.from,subject: payload.subject,text: payload.text,to: toRecipients- };-- logger.info("Resend Email Job");- const response = await resend.emails.send(email);+ });if (response.error) {- if (response.error.name === "validation_error") {+ // A rejected envelope (bad recipient/sender address) will never+ // succeed on retry.+ if ((response.error as { code?: string }).code === "EENVELOPE") {throw new NonRetriableError(- `Resend validation error: ${serializeError(response.error)}`+ `Email envelope error: ${response.error.message}`);}- throw new Error(`Resend error: ${serializeError(response.error)}`);+ throw new Error(`Email error: ${response.error.message}`);}+ // data is null when SMTP is not configured — email is disabled.return response.data;});// Count the delivery for recurring notifications (result is null when- // Resend is disabled). Throwing here is retry-safe: the memoized send step- // won't re-send, and the memoized Resend id makes the increment idempotent.+ // email is disabled). Throwing here is retry-safe: the memoized send step+ // won't re-send, and the memoized message id makes the increment idempotent.const tracking = payload.tracking;if (tracking && result) {await step.run("record-delivery", async () => {diff --git a/packages/jobs/src/inngest/functions/tasks/onboard.ts b/packages/jobs/src/inngest/functions/tasks/onboard.tsindex 60b7bebe16..9b6d8a0138 100644--- a/packages/jobs/src/inngest/functions/tasks/onboard.ts+++ b/packages/jobs/src/inngest/functions/tasks/onboard.ts@@ -2,8 +2,8 @@ import { openai } from "@ai-sdk/openai";import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { Database } from "@carbon/database";import { GetStartedEmail, WelcomeEmail } from "@carbon/documents/email";-import { RESEND_DOMAIN } from "@carbon/env";-import { getResend, sendEmail } from "@carbon/lib/resend.server";+import { EMAIL_DOMAIN, sendEmail } from "@carbon/lib/email.server";+import { getResend } from "@carbon/lib/resend.server";import { getSlackClient } from "@carbon/lib/slack.server";import { getTwentyClient } from "@carbon/lib/twenty.server";import { render } from "@react-email/components";@@ -277,9 +277,9 @@ export const onboardFunction = inngest.createFunction(if (sendOnboardingEmail) {const from = `Chase from Carbon <${- RESEND_DOMAIN === "carbon.ms"+ EMAIL_DOMAIN === "carbon.ms"- : `no-reply@${RESEND_DOMAIN}`+ : `no-reply@${EMAIL_DOMAIN}`}>`;await step.run("send-welcome-email", async () => {await sendEmail({@@ -295,9 +295,9 @@ export const onboardFunction = inngest.createFunction(if (sendOnboardingEmail) {const from = `Info from Carbon <${- RESEND_DOMAIN === "carbon.ms"+ EMAIL_DOMAIN === "carbon.ms"- : `no-reply@${RESEND_DOMAIN}`+ : `no-reply@${EMAIL_DOMAIN}`}>`;await step.run("send-get-started-email", async () => {await sendEmail({diff --git a/packages/jobs/src/inngest/functions/tasks/user-admin.ts b/packages/jobs/src/inngest/functions/tasks/user-admin.tsindex 998fe28180..646c1feffe 100644--- a/packages/jobs/src/inngest/functions/tasks/user-admin.ts+++ b/packages/jobs/src/inngest/functions/tasks/user-admin.ts@@ -3,12 +3,8 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { deactivateUser } from "@carbon/auth/users.server";import { InviteEmail } from "@carbon/documents/email";import { getSsoAwareInviteLink } from "@carbon/ee/sso.server";-import {- CarbonEdition,- CONTROLLED_ENVIRONMENT,- RESEND_DOMAIN-} from "@carbon/env";-import { sendEmail } from "@carbon/lib/resend.server";+import { CarbonEdition, CONTROLLED_ENVIRONMENT } from "@carbon/env";+import { sendEmail } from "@carbon/lib/email.server";import { updateSubscriptionQuantityForCompany } from "@carbon/stripe/stripe.server";import { Edition } from "@carbon/utils";import { render } from "@react-email/components";@@ -105,7 +101,6 @@ export const userAdminFunction = inngest.createFunction();await sendEmail({- from: `Carbon <no-reply@${RESEND_DOMAIN}>`,to: user.data.email,subject: `You have been invited to join ${company.data?.name} on Carbon`,headers: {diff --git a/packages/lib/AGENTS.md b/packages/lib/AGENTS.mdindex b70974210b..e1b5156624 100644--- a/packages/lib/AGENTS.md+++ b/packages/lib/AGENTS.md@@ -1,13 +1,13 @@# @carbon/lib-Shared server utilities — event system, Inngest client, trigger dispatch, Resend email, Slack messaging, and Twenty CRM.+Shared server utilities — event system, Inngest client, trigger dispatch, SMTP email, Slack messaging, and Twenty CRM.## Always- **Use `trigger(taskId, payload)` for dispatching background jobs** — typed helper that maps task IDs to Inngest event names; drop-in replacement for old `tasks.trigger()`- **Add new events to the `Events` type in `events.ts`** — every Inngest event needs a typed payload here- **Add new task mappings to `taskToEvent` in `trigger.ts`** — maps human-readable task IDs to `carbon/*` event names-- **Guard external calls** — `resend.server.ts` respects `DISABLE_RESEND` env; `slack.server.ts` skips sends on localhost+- **Guard external calls** — `email.server.ts` no-ops when no SMTP config is set (`SMTP_*`, with a legacy `RESEND_API_KEY` fallback via smtp.resend.com); `slack.server.ts` skips sends on localhost- **Add new work events to `src/telemetry/events.ts`** — the `WorkEvents` type map is the contract; `captureWorkEvent` is typed off it, so an unlisted name will not compile## Ask First@@ -32,7 +32,7 @@ pnpm --filter @carbon/lib test # vitest run- **Inngest client**: `src/inngest/client.ts` — singleton `new Inngest({ id: "carbon", logger: createInngestLogger() })`. The `logger` (from `@carbon/logger/inngest`) routes every job's `ctx.logger` into LogTape under the `["carbon","jobs"]` category.- **Trigger helper**: `trigger(taskId, payload)` / `batchTrigger(taskId, items)` — typed dispatch- **Events**: `src/events.ts` — full `Events` type map (`carbon/notify`, `carbon/send-email`, `carbon/send-slack`, etc.)-- **Exports**: `./events`, `./inngest`, `./trigger`, `./telemetry`, `./resend.server`, `./slack.server`, `./twenty.server`+- **Exports**: `./events`, `./inngest`, `./trigger`, `./telemetry`, `./email.server` (SMTP `sendEmail`, `DEFAULT_FROM`, `EMAIL_DOMAIN`), `./resend.server` (marketing contacts only), `./slack.server`, `./twenty.server`- **Work-event telemetry**: `src/telemetry/` — `trackWorkEvent()` records work done on the platform (jobs released, quotes sent, POs issued) as a PostHog event, over a bare `fetch` with no SDK. Three rules it must keep: it **never throws into the caller** (same contract as `raiseMoment` — a lost measurement beats a failed action), the event `uuid` is **deterministic** from (companyId, event, recordId, discriminator) so a retry collapses instead of double-counting, and it emits only when `POSTHOG_PROJECT_PUBLIC_KEY` is set and `CONTROLLED_ENVIRONMENT` is off — the same gate `apps/erp/app/entry.client.tsx:31` puts on the browser SDK. Deliberately **not** named `.server`: MES service files are in the client graph (React components import their types), so a `.server` specifier fails the React Router build — which is also why the hash is plain TypeScript rather than `node:crypto`. See `src/telemetry/README.md` for the coverage gaps and `VERIFICATION.md` for the post-deploy runbook- **Workflow moments**: `src/workflows/raise-moment.ts` — `raiseMoment()` announces a business moment (as opposed to a row change) to the workflow matcher. Two rules it must keep: it **never throws into the caller** (a failed announcement must not fail the business operation that raised it — it logs instead), and the `momentId` it mints is used twice, as the Inngest event id *and* as the matcher's `sourceEventId`, which is what makes a redelivery idempotent. See `.claude/rules/workflow-matcher.md`@@ -40,5 +40,5 @@ pnpm --filter @carbon/lib test # vitest run- `packages/notifications/` — `NotificationEvent` / `NotificationDestination` enums used in event payloads- `packages/jobs/` — Inngest function implementations that consume these events-- `packages/env/` — `SLACK_BOT_TOKEN`, `RESEND_API_KEY`, and other env vars+- `packages/env/` — `SLACK_BOT_TOKEN`, `SMTP_*`, and other env vars- `packages/logger/` — `createInngestLogger()` wired as the Inngest client's `logger`diff --git a/packages/lib/package.json b/packages/lib/package.jsonindex 0801cbebcb..9ee5fdac13 100644--- a/packages/lib/package.json+++ b/packages/lib/package.json@@ -11,6 +11,7 @@"@supabase/supabase-js": "catalog:","inngest": "3.54.0","nanoid": "catalog:",+ "nodemailer": "9.0.1","resend": "3.5.0","sst": "catalog:","supabase": "catalog:",@@ -19,6 +20,7 @@"devDependencies": {"@carbon/config": "workspace:*","@types/node": "20.19.39",+ "@types/nodemailer": "6.4.23","dotenv": "16.3.1","rimraf": "catalog:","tsup": "catalog:",@@ -28,6 +30,7 @@},"exports": {"./async": "./src/async.ts",+ "./email.server": "./src/email.server.ts","./events": "./src/events.ts","./inngest": "./src/inngest/client.ts","./resend.server": "./src/resend.server.ts",diff --git a/packages/lib/src/email.server.test.ts b/packages/lib/src/email.server.test.tsnew file mode 100644index 0000000000..ba3ea588a5--- /dev/null+++ b/packages/lib/src/email.server.test.ts@@ -0,0 +1,187 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const createTransport = vi.fn();+const sendMail = vi.fn();++vi.mock("nodemailer", () => ({+ default: { createTransport }+}));++// The real @carbon/env throws at import on unrelated required vars; mirror just+// the SMTP accessors, reading process.env lazily so vi.stubEnv applies.+vi.mock("@carbon/env", () => ({+ get SMTP_FROM() {+ return process.env.SMTP_FROM || undefined;+ },+ get SMTP_HOST() {+ return process.env.SMTP_HOST || undefined;+ },+ get SMTP_PASSWORD() {+ return process.env.SMTP_PASSWORD || undefined;+ },+ get SMTP_PORT() {+ return Number(process.env.SMTP_PORT ?? 587);+ },+ get SMTP_USER() {+ return process.env.SMTP_USER || undefined;+ }+}));++vi.mock("@carbon/logger", () => ({+ getLogger: () => ({+ debug: vi.fn(),+ info: vi.fn(),+ error: vi.fn()+ })+}));++// @carbon/env reads process.env at import time, so each test stubs env and+// re-imports the module fresh.+const loadMailer = async () => {+ vi.resetModules();+ return import("./email.server");+};++describe("sendEmail", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ createTransport.mockReturnValue({ sendMail });+ sendMail.mockResolvedValue({ messageId: "msg-1" });+ for (const key of [+ "SMTP_HOST",+ "SMTP_PORT",+ "SMTP_USER",+ "SMTP_PASSWORD",+ "SMTP_FROM",+ "RESEND_API_KEY",+ "RESEND_DOMAIN"+ ]) {+ vi.stubEnv(key, "");+ Reflect.deleteProperty(process.env, key);+ }+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it("uses implicit TLS on port 465", async () => {+ vi.stubEnv("SMTP_HOST", "mail.example.com");+ vi.stubEnv("SMTP_PORT", "465");+ vi.stubEnv("SMTP_USER", "user");+ vi.stubEnv("SMTP_PASSWORD", "pass");++ const { sendEmail } = await loadMailer();+ await sendEmail({ to: "[email protected]", subject: "hi", text: "hello" });++ expect(createTransport).toHaveBeenCalledWith({+ host: "mail.example.com",+ port: 465,+ secure: true,+ requireTLS: false,+ auth: { user: "user", pass: "pass" }+ });+ });++ it("uses STARTTLS (secure: false) on port 587, required when authenticated", async () => {+ vi.stubEnv("SMTP_HOST", "mail.example.com");+ vi.stubEnv("SMTP_PORT", "587");+ vi.stubEnv("SMTP_USER", "user");+ vi.stubEnv("SMTP_PASSWORD", "pass");++ const { sendEmail } = await loadMailer();+ await sendEmail({ to: "[email protected]", subject: "hi", text: "hello" });++ expect(createTransport).toHaveBeenCalledWith(+ expect.objectContaining({ port: 587, secure: false, requireTLS: true })+ );+ });++ it("allows plaintext for an unauthenticated relay", async () => {+ vi.stubEnv("SMTP_HOST", "relay.internal");+ vi.stubEnv("SMTP_PORT", "25");++ const { sendEmail } = await loadMailer();+ await sendEmail({ to: "[email protected]", subject: "hi", text: "hello" });++ expect(createTransport).toHaveBeenCalledWith(+ expect.objectContaining({ requireTLS: false, auth: undefined })+ );+ });++ it("defaults from to SMTP_FROM and returns the message id", async () => {+ vi.stubEnv("SMTP_HOST", "mail.example.com");+ vi.stubEnv("SMTP_FROM", "Acme <[email protected]>");++ const { sendEmail } = await loadMailer();+ const result = await sendEmail({+ to: "[email protected]",+ subject: "hi",+ html: "<p/>"+ });++ expect(sendMail).toHaveBeenCalledWith(+ expect.objectContaining({ from: "Acme <[email protected]>", to: "[email protected]" })+ );+ expect(result).toEqual({ data: { id: "msg-1" }, error: null });+ });++ it("falls back to Resend SMTP when only RESEND_API_KEY is set", async () => {+ vi.stubEnv("RESEND_API_KEY", "re_123");++ const { sendEmail } = await loadMailer();+ await sendEmail({ to: "[email protected]", subject: "hi", text: "hello" });++ expect(createTransport).toHaveBeenCalledWith({+ host: "smtp.resend.com",+ port: 465,+ secure: true,+ auth: { user: "resend", pass: "re_123" }+ });+ });++ it("prefers SMTP_* over the Resend fallback when both are set", async () => {+ vi.stubEnv("SMTP_HOST", "mail.example.com");+ vi.stubEnv("RESEND_API_KEY", "re_123");++ const { sendEmail } = await loadMailer();+ await sendEmail({ to: "[email protected]", subject: "hi", text: "hello" });++ expect(createTransport).toHaveBeenCalledWith(+ expect.objectContaining({ host: "mail.example.com" })+ );+ });++ it("no-ops without error when nothing is configured", async () => {+ const { sendEmail } = await loadMailer();+ const result = await sendEmail({ to: "[email protected]", subject: "hi", text: "x" });++ expect(result).toEqual({ data: null, error: null });+ expect(createTransport).not.toHaveBeenCalled();+ expect(sendMail).not.toHaveBeenCalled();+ });++ it("returns the error instead of throwing when the transport fails", async () => {+ vi.stubEnv("SMTP_HOST", "mail.example.com");+ sendMail.mockRejectedValueOnce(new Error("connect ECONNREFUSED"));++ const { sendEmail } = await loadMailer();+ const result = await sendEmail({ to: "[email protected]", subject: "hi", text: "x" });++ expect(result.data).toBeNull();+ expect(result.error?.message).toBe("connect ECONNREFUSED");+ });++ it("derives EMAIL_DOMAIN from the from-address", async () => {+ vi.stubEnv("SMTP_FROM", "Acme <[email protected]>");+ expect((await loadMailer()).EMAIL_DOMAIN).toBe("acme.com");++ vi.stubEnv("SMTP_FROM", "");+ Reflect.deleteProperty(process.env, "SMTP_FROM");+ vi.stubEnv("RESEND_DOMAIN", "legacy.dev");+ expect((await loadMailer()).EMAIL_DOMAIN).toBe("legacy.dev");++ Reflect.deleteProperty(process.env, "RESEND_DOMAIN");+ expect((await loadMailer()).EMAIL_DOMAIN).toBe("carbon.ms");+ });+});diff --git a/packages/lib/src/email.server.ts b/packages/lib/src/email.server.tsnew file mode 100644index 0000000000..f398a2efb5--- /dev/null+++ b/packages/lib/src/email.server.ts@@ -0,0 +1,132 @@+import {+ SMTP_FROM,+ SMTP_HOST,+ SMTP_PASSWORD,+ SMTP_PORT,+ SMTP_USER+} from "@carbon/env";+import { getLogger } from "@carbon/logger";+import type { Transporter } from "nodemailer";+import nodemailer from "nodemailer";++const log = getLogger("lib", "email");++export type SendEmailPayload = {+ /** Defaults to DEFAULT_FROM (SMTP_FROM). */+ from?: string;+ to: string | string[];+ cc?: string | string[];+ bcc?: string | string[];+ replyTo?: string;+ subject: string;+ text?: string;+ html?: string;+ headers?: Record<string, string>;+ attachments?: Array<+ { filename: string; content: string } | { filename: string; path: string }+ >;+};++export type SendEmailResult = {+ data: { id: string } | null;+ error: Error | null;+};++export const DEFAULT_FROM =+ SMTP_FROM ?? `Carbon <no-reply@${process.env.RESEND_DOMAIN ?? "carbon.ms"}>`;++/** Domain of the default from-address, e.g. "carbon.ms". */+export const EMAIL_DOMAIN =+ DEFAULT_FROM.match(/@([^>\s]+)/)?.[1] ?? "carbon.ms";++/**+ * Built on first send, not at import.+ *+ * The old Resend client was `new Resend(process.env.RESEND_API_KEY!)` at+ * module scope, and its constructor throws when the key is missing. Every+ * route bundle that imported `sendEmail` therefore evaluated it at boot, so+ * a deployment with no mail config did not lose email — it lost the whole+ * server, crash-looping before it served a request. Same rule applies to+ * the SMTP transport: an unconfigured install has opted out of email, and+ * inviting a user should not fail with a stack trace about mail servers.+ */+let transporter: Transporter | null | undefined;++const getTransporter = (): Transporter | null => {+ if (transporter !== undefined) return transporter;++ if (SMTP_HOST) {+ const auth =+ SMTP_USER && SMTP_PASSWORD+ ? { user: SMTP_USER, pass: SMTP_PASSWORD }+ : undefined;+ transporter = nodemailer.createTransport({+ host: SMTP_HOST,+ port: SMTP_PORT,+ secure: SMTP_PORT === 465,+ // Never send credentials in plaintext if the relay skips STARTTLS.+ requireTLS: SMTP_PORT !== 465 && Boolean(auth),+ auth+ });+ } else if (process.env.RESEND_API_KEY) {+ // Legacy fallback so existing deployments keep sending with zero config+ // change: Resend's SMTP interface accepts the API key as the password.+ log.info(+ "SMTP_* not set — falling back to RESEND_API_KEY via smtp.resend.com; migrate to SMTP_* vars"+ );+ transporter = nodemailer.createTransport({+ host: "smtp.resend.com",+ port: 465,+ secure: true,+ auth: { user: "resend", pass: process.env.RESEND_API_KEY }+ });+ } else {+ log.info("SMTP not configured — email disabled");+ transporter = null;+ }++ return transporter;+};++export const sendEmail = async (+ payload: SendEmailPayload+): Promise<SendEmailResult> => {+ const transport = getTransporter();++ if (!transport) {+ // Log only non-sensitive metadata — the full payload carries recipient PII+ // and the rendered HTML body (which can include verification codes).+ log.debug("Email send skipped (SMTP not configured)", {+ to: payload.to,+ subject: payload.subject+ });+ return { data: null, error: null };+ }++ try {+ const info = await transport.sendMail({+ from: payload.from ?? DEFAULT_FROM,+ to: payload.to,+ cc: payload.cc,+ bcc: payload.bcc,+ replyTo: payload.replyTo,+ subject: payload.subject,+ text: payload.text,+ html: payload.html,+ headers: payload.headers,+ attachments: payload.attachments?.map((attachment) =>+ "content" in attachment+ ? { ...attachment, encoding: "base64" as const }+ : attachment+ )+ });+ return { data: { id: info.messageId }, error: null };+ } catch (err) {+ log.error("Email send failed", {+ to: payload.to,+ subject: payload.subject,+ error: err+ });+ return { data: null, error: err as Error };+ }+};diff --git a/packages/lib/src/resend.server.ts b/packages/lib/src/resend.server.tsindex e3b580642b..3469bacb0e 100644--- a/packages/lib/src/resend.server.ts+++ b/packages/lib/src/resend.server.ts@@ -1,26 +1,10 @@-import { getLogger } from "@carbon/logger";-import type {- CreateEmailOptions,- CreateEmailRequestOptions,- CreateEmailResponse-} from "resend";import { Resend } from "resend";-const log = getLogger("lib", "resend");-/**- * Built on first send, not at import.- *- * This was `export const resend = new Resend(process.env.RESEND_API_KEY!)`- * at module scope, and Resend's constructor throws when the key is- * missing. Every route bundle that imports `sendEmail` therefore evaluated- * it at boot, so a deployment with no RESEND_API_KEY did not lose email —- * it lost the whole server, crash-looping on "Missing API key" before it- * served a request. The `!` was the tell: it asserted a value that- * genuinely is absent in a self-hosted install.- *- * The DISABLE_RESEND guard below could never help, because the throw- * happened at import time, long before anything called sendEmail.+ * Resend is no longer the email transport (see email.server.ts) — this+ * client exists only for the marketing-contacts/audience API, which has no+ * SMTP equivalent. Built lazily so an install without a key never evaluates+ * the constructor (it throws on a missing key).*/let client: Resend | undefined;@@ -30,39 +14,3 @@ export const getResend = (): Resend | undefined => {if (!client) client = new Resend(key);return client;};--export const sendEmail = async (- payload: CreateEmailOptions,- options?: CreateEmailRequestOptions-): Promise<CreateEmailResponse> => {- const resend = getResend();-- // No key configured is the same outcome as DISABLE_RESEND, and- // deliberately not an error: a self-hosted deployment that never set one- // has opted out of email, and inviting a user should not fail with a- // stack trace about someone else's SaaS.- if (!resend) {- log.debug("Email send skipped (no RESEND_API_KEY)", {- to: payload.to,- subject: payload.subject- });- return {- error: null,- data: null- };- }-- if (process.env.DISABLE_RESEND) {- // Log only non-sensitive metadata — the full payload carries recipient PII- // and the rendered HTML body (which can include verification codes).- log.debug("Email send skipped (DISABLE_RESEND)", {- to: payload.to,- subject: payload.subject- });- return {- error: null,- data: null- };- }- return resend.emails.send(payload, options);-};diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 992bf3e208..6cf9194757 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2669,9 +2669,6 @@ importers:nanoid:specifier: 'catalog:'version: 5.1.16- nodemailer:- specifier: 9.0.1- version: 9.0.1pdfjs-dist:specifier: 5.4.296version: 5.4.296@@ -2684,9 +2681,6 @@ importers:react-pdf:specifier: 'catalog:'- resend:- specifier: 3.5.0sst:specifier: 'catalog:'version: 4.6.9@@ -2706,9 +2700,6 @@ importers:'@carbon/config':specifier: workspace:*version: link:../config- '@types/nodemailer':- specifier: 6.4.23- version: 6.4.23'@types/pg':specifier: 8.15.6version: 8.15.6@@ -2815,6 +2806,9 @@ importers:nanoid:specifier: 'catalog:'version: 5.1.16+ nodemailer:+ specifier: 9.0.1+ version: 9.0.1resend:specifier: 3.5.0@@ -2834,6 +2828,9 @@ importers:'@types/node':specifier: 20.19.39version: 20.19.39+ '@types/nodemailer':+ specifier: 6.4.23+ version: 6.4.23dotenv:specifier: 16.3.1version: 16.3.1diff --git a/scripts/lib/validator-loader.ts b/scripts/lib/validator-loader.tsindex 608a97ba6e..cce62c703f 100644--- a/scripts/lib/validator-loader.ts+++ b/scripts/lib/validator-loader.ts@@ -61,7 +61,6 @@ const ENV_PLACEHOLDERS: Record<string, string> = {VERCEL_URL: "localhost",POSTHOG_API_HOST: "http://localhost",POSTHOG_PROJECT_PUBLIC_KEY: "placeholder",- RESEND_API_KEY: "re_placeholder",};function applyEnvPlaceholders(): void {diff --git a/sst.config.ts b/sst.config.tsindex 5cdbdcc41b..5ae1c9af35 100644--- a/sst.config.ts+++ b/sst.config.ts@@ -82,7 +82,11 @@ export default $config({QUICKBOOKS_WEBHOOK_SECRET: process.env.QUICKBOOKS_WEBHOOK_SECRET,RESEND_API_KEY: process.env.RESEND_API_KEY,REDIS_URL: process.env.REDIS_URL,- RESEND_DOMAIN: process.env.RESEND_DOMAIN ?? "carbon.ms",+ SMTP_FROM: process.env.SMTP_FROM,+ SMTP_HOST: process.env.SMTP_HOST,+ SMTP_PASSWORD: process.env.SMTP_PASSWORD,+ SMTP_PORT: process.env.SMTP_PORT,+ SMTP_USER: process.env.SMTP_USER,SESSION_SECRET: process.env.SESSION_SECRET,SLACK_BOT_TOKEN: process.env.SLACK_BOT_TOKEN,SLACK_CLIENT_ID: process.env.SLACK_CLIENT_ID,@@ -180,7 +184,11 @@ export default $config({POSTHOG_PROJECT_PUBLIC_KEY: process.env.POSTHOG_PROJECT_PUBLIC_KEY,REDIS_URL: process.env.REDIS_URL,RESEND_API_KEY: process.env.RESEND_API_KEY,- RESEND_DOMAIN: process.env.RESEND_DOMAIN ?? "carbon.ms",+ SMTP_FROM: process.env.SMTP_FROM,+ SMTP_HOST: process.env.SMTP_HOST,+ SMTP_PASSWORD: process.env.SMTP_PASSWORD,+ SMTP_PORT: process.env.SMTP_PORT,+ SMTP_USER: process.env.SMTP_USER,SESSION_SECRET: process.env.SESSION_SECRET,SUPABASE_ANON_KEY: process.env.SUPABASE_ANON_KEY,SUPABASE_DB_URL: process.env.SUPABASE_DB_URL,