Lumen & Gesso / website · lumengesso.com / app / lib / email.ts
| 1 | import 'server-only'; |
| 2 | import { getCloudflareContext } from '@opennextjs/cloudflare'; |
| 3 | import { env } from './env'; |
| 4 | |
| 5 | // Cloudflare Email Service (2026-11-27: everything moved off Resend). lumengesso.com is |
| 6 | // onboarded for Email Sending; wrangler.jsonc binds it as EMAIL. Sign-in links and every |
| 7 | // order email go through sendEmail below. |
| 8 | |
| 9 | type SendArgs = { |
| 10 | to: string; |
| 11 | subject: string; |
| 12 | html: string; |
| 13 | text?: string; |
| 14 | /** Override default reply-to (defaults to hello@lumengesso.com). */ |
| 15 | replyTo?: string; |
| 16 | }; |
| 17 | type Address = string | { email: string; name?: string }; |
| 18 | type Binding = { send: (m: Record<string, unknown>) => Promise<{ messageId?: string }> }; |
| 19 | |
| 20 | // Default reply-to. Real, monitored address routed through Cloudflare |
| 21 | // Email Routing. Setting a Reply-To is a strong "real business" signal for |
| 22 | // Gmail / Outlook spam filters and lets customers actually respond to receipts. |
| 23 | const DEFAULT_REPLY_TO = 'hello@lumengesso.com'; |
| 24 | |
| 25 | // "Name <a@b.c>" -> { email, name } |
| 26 | const addr = (a: string): Address => { |
| 27 | const m = a.match(/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/); |
| 28 | return m ? (m[1] ? { email: m[2].trim(), name: m[1].trim() } : m[2].trim()) : a.trim(); |
| 29 | }; |
| 30 | |
| 31 | export async function sendEmail({ to, subject, html, text, replyTo }: SendArgs) { |
| 32 | let binding: Binding | undefined; |
| 33 | try { |
| 34 | binding = (getCloudflareContext().env as unknown as { EMAIL?: Binding }).EMAIL; |
| 35 | } catch {} |
| 36 | if (!binding) throw new Error('Email error: the EMAIL binding is not available'); |
| 37 | try { |
| 38 | const r = await binding.send({ |
| 39 | from: addr(env.email.from()), |
| 40 | to: addr(to), |
| 41 | replyTo: addr(replyTo ?? DEFAULT_REPLY_TO), |
| 42 | subject, |
| 43 | html, |
| 44 | ...(text ? { text } : {}), |
| 45 | }); |
| 46 | return { id: r?.messageId }; |
| 47 | } catch (e) { |
| 48 | throw new Error(`Email error: ${e instanceof Error ? e.message : String(e)}`); |
| 49 | } |
| 50 | } |