How to Send Email with SvelteKit (2026)
Pranav Patel
Co-founder·10 min read
On this page

Send transactional email from SvelteKit 2 and Svelte 5 with Reloop: a server-only client, form actions with progressive enhancement, +server.ts API routes, error handling, templates and deployment.
To send email from SvelteKit, call Reloop only from server code: a form action in +page.server.ts or an endpoint in +server.ts. Keep the client in src/lib/server/ and read the API key from $env/static/private, and SvelteKit will refuse to bundle either into the browser.
This guide builds both patterns end to end on SvelteKit 2 and Svelte 5: install, a shared client, a contact form with progressive enhancement, a JSON endpoint for webhooks and cron, error handling, templates and deploys.
Using another framework? See the Next.js, Remix or plain Node.js guides.
What you'll build
src/routes/contact/+page.server.tssrc/routes/api/send/+server.tsBoth run only on the server and both use the same Reloop call. Use form actions for your UI. Use +server.ts when something outside your app needs a URL to POST to.
Prerequisites
- A SvelteKit 2 project (
npx sv create my-appif you're starting fresh) - A Reloop account and an API key from the dashboard. Keys start with
rl_. - A verified sending domain. See connect a domain and the SPF, DKIM and DMARC guide.
1. Install the SDK
npm install reloop-emailThe package is reloop-email. It's written in TypeScript, so you get types for every field without extra packages.
2. Add the API key
Create .env in the project root:
RELOOP_API_KEY=rl_your_api_key_hereSvelteKit splits environment variables into public and private:
$env/static/private$env/dynamic/private$env/static/publicPUBLIC_ prefix)$env/dynamic/publicIf you import a private module from client-side code, the build fails. That's the guardrail you want.
3. Create a server-only client
Put the client in src/lib/server/. SvelteKit won't let any file under that folder be imported into code that runs in the browser.
1import { RELOOP_API_KEY } from "$env/static/private";2import { Reloop } from "reloop-email";3
4export const reloop = new Reloop({ apiKey: RELOOP_API_KEY });The constructor takes an options object: { apiKey }, plus an optional baseUrl if you self-host Reloop.
4. Send from a form action
Form actions are the most natural fit. They work without JavaScript, and use:enhance upgrades them to a smooth in-page submit when JavaScript is available.
The action
1// src/routes/contact/+page.server.ts2import { fail } from "@sveltejs/kit";3import { reloop } from "$lib/server/reloop";4import type { Actions } from "./$types";5
6export const actions = {7 default: async ({ request }) => {8 const data = await request.formData();9 const email = String(data.get("email") ?? "").trim().toLowerCase();10 const message = String(data.get("message") ?? "").trim();11
12 if (!email.includes("@")) {13 return fail(400, { email, message, error: "Enter a valid email." });14 }15 if (message.length < 10) {16 return fail(400, { email, message, error: "Tell us a bit more." });17 }18
19 const { response, emailError } = await reloop.mail.send({20 from: "Acme <hello@mail.acme.com>",21 to: email,22 reply_to: "support@acme.com",23 subject: "We got your message",24 html: `<p>Thanks for reaching out. We'll reply within one business day.</p>`,25 text: "Thanks for reaching out. We'll reply within one business day.",26 tags: [{ name: "type", value: "contact_confirmation" }],27 });28
29 if (emailError) {30 console.error("Reloop send failed", emailError.status, emailError.body);31 return fail(502, { email, message, error: "Couldn't send. Try again." });32 }33
34 return { success: true, id: response.messageId };35 },36} satisfies Actions;A few things worth noting:
reloop.mail.senddoesn't throw on API errors. It returns{ response, emailError }, so failures are a normal branch in your code.emailError.bodycarries Reloop's structured error: amessage,why,fixand docslink. Log it on the server. Don't send it to the user.fail()returns the submitted values, so the form can be re-filled after a validation error.frommust be on a domain you've verified in Reloop.
The page
1<!-- src/routes/contact/+page.svelte -->2<script lang="ts">3 import { enhance } from "$app/forms";4 import type { PageProps } from "./$types";5
6 let { form }: PageProps = $props();7 let sending = $state(false);8</script>9
10{#if form?.success}11 <p>Thanks! Check your inbox for a confirmation.</p>12{:else}13 <form14 method="POST"15 use:enhance={() => {16 sending = true;17 return async ({ update }) => {18 await update();19 sending = false;20 };21 }}22 >23 <input name="email" type="email" value={form?.email ?? ""} required />24 <textarea name="message" required>{form?.message ?? ""}</textarea>25
26 {#if form?.error}<p class="error">{form.error}</p>{/if}27
28 <button disabled={sending}>{sending ? "Sending…" : "Send"}</button>29 </form>30{/if}This uses Svelte 5 runes: $props() for the action result and $state() for the pending flag. Without JavaScript, the form still posts and the page re-renders with form filled in.
5. Send from a +server.ts endpoint
Use an endpoint when the caller isn't your own UI: a Stripe webhook, a cron job, a mobile app, an AI agent.
1// src/routes/api/send/+server.ts2import { error, json } from "@sveltejs/kit";3import { INTERNAL_SEND_SECRET } from "$env/static/private";4import { reloop } from "$lib/server/reloop";5import type { RequestHandler } from "./$types";6
7type Body = { to?: string; name?: string };8
9export const POST: RequestHandler = async ({ request }) => {10 if (request.headers.get("x-internal-secret") !== INTERNAL_SEND_SECRET) {11 error(401, "Unauthorized");12 }13
14 const body = (await request.json().catch(() => ({}))) as Body;15 const to = body.to?.trim().toLowerCase();16 if (!to?.includes("@")) error(400, "Field `to` must be an email");17
18 const { response, emailError } = await reloop.mail.send({19 from: "Acme <onboarding@mail.acme.com>",20 to,21 subject: body.name ? `Welcome, ${body.name}` : "Welcome to Acme",22 html: "<p>Your account is ready.</p>",23 text: "Your account is ready.",24 });25
26 if (emailError) {27 console.error("Reloop send failed", emailError.status, emailError.body);28 error(502, "Failed to send email");29 }30
31 return json({ ok: true, messageId: response.messageId });32};Test it locally:
1curl -X POST http://localhost:5173/api/send \2 -H "Content-Type: application/json" \3 -H "x-internal-secret: $INTERNAL_SEND_SECRET" \4 -d '{"to":"you@example.com","name":"Ada"}'In SvelteKit 2, error() throws for you, so there's no throw keyword in front of it.
6. Form action or endpoint?
+server.tsMost apps end up using both: actions for product UI, endpoints for integrations.
7. Use a template instead of inline HTML
Inline HTML is fine for a contact form. For anything you'll iterate on (welcome emails, receipts, password resets), keep the design in a Reloop template and send variables from code.
1await reloop.mail.send({2 from: "Acme <hello@mail.acme.com>",3 to: user.email,4 subject: "Reset your password",5 template: {6 id: "tmpl_password_reset",7 variables: { name: user.name, reset_url: resetUrl },8 },9});Templates use {{variable}} placeholders. Designers can edit them in the dashboard without a deploy.
8. Fields you'll use most
1await reloop.mail.send({2 from: "Acme <hello@mail.acme.com>", // required, verified domain3 to: ["a@example.com", "b@example.com"], // string or array, up to 504 subject: "Order shipped", // required5 html: "<p>Your order is on its way.</p>",6 text: "Your order is on its way.", // plain-text fallback7 reply_to: "support@acme.com",8 cc: "ops@acme.com",9 bcc: "archive@acme.com",10 scheduled_at: "2026-02-25T09:00:00Z", // send later (ISO 8601)11 tags: [{ name: "type", value: "shipping" }],12 attachments: [{ filename: "invoice.pdf", content: base64Pdf }],13});The full list is in the send email API reference.
9. Deploying
The SDK sends over fetch, so it runs on any SvelteKit adapter: adapter-node, Vercel, Netlify and Cloudflare.
RELOOP_API_KEYadapter-node.envstatic, at runtime with dynamicwrangler secret put RELOOP_API_KEY$env/dynamic/private for runtime secrets$env/static/private inlines the value at build time. If your platform only exposes secrets at runtime, import from $env/dynamic/private instead:
1import { env } from "$env/dynamic/private";2import { Reloop } from "reloop-email";3
4export const reloop = new Reloop({ apiKey: env.RELOOP_API_KEY! });For Cloudflare specifics, see sending email from Cloudflare Workers.
Production checklist
- API key only in private env, never
PUBLIC_ - Client lives in
src/lib/server/ - Sending domain verified with SPF, DKIM and DMARC
-
emailErrorhandled and logged server-side - Public endpoints gated and rate-limited
- Plain-text version included alongside HTML
FAQ
No. +page.ts and components can run in the browser. Send only from
+page.server.ts, +layout.server.ts, +server.ts or hooks.server.ts.
The browser calls those, never Reloop directly.
Yes. Point Nodemailer at smtp.reloop.sh on port 587 with your API key as
both username and password. See the SMTP docs.
The SDK is simpler on serverless platforms because it's a single HTTPS
request.
Call reloop.mail.send inside the form action or endpoint that creates the
user, after the database write succeeds. For multi-step onboarding, start a
Reloop automation from that same spot instead.
Send to your own address while developing, and use tags like
{ name: "env", value: "dev" } so you can filter test sends in the logs.
Ship your first email with Reloop
in minutes.
Open-source, deliverability-focused, and yours to self-host or run on Reloop Cloud. No lock-in, no rewrite later.


