In SvelteKit, send email from a form action: the <form> posts to +page.server.ts, the action validates the input and calls an email API with fetch, and the API key never leaves the server. The form works without JavaScript and gets a smoother experience with use:enhance. This guide uses SvelteKit 3 and Svelte 5 and sends through Mailcandor; other email APIs need only a different URL and body.
Step 1: declare the API key as a private variable
SvelteKit 3 introduces explicit environment variables. Declare the key in src/env.ts:
// src/env.ts
import { defineEnvVars } from '@sveltejs/kit/env';
export const variables = defineEnvVars({
MAILCANDOR_KEY: {}
});
Variables are private by default, and private variables can only be imported from $app/env/private. The SvelteKit environment variable docs explain that this module cannot be imported into code that runs in the browser, so the key cannot leak into a bundle by accident. Variables are read at runtime unless you mark them static: true.
Put the value in .env.local for development and in your host’s environment settings in production:
MAILCANDOR_KEY=mc_live_...
On SvelteKit 2, use import { MAILCANDOR_KEY } from '$env/static/private' instead. That module still works in SvelteKit 3 but is deprecated.
Step 2: write the form action
// src/routes/contact/+page.server.ts
import { fail } from '@sveltejs/kit';
import { MAILCANDOR_KEY } from '$app/env/private';
import type { Actions } from './$types';
export const actions = {
default: async ({ request, fetch }) => {
const data = await request.formData();
const email = String(data.get('email') ?? '').trim();
const message = String(data.get('message') ?? '').trim();
if (!email.includes('@') || !message) {
return fail(400, { email, message, invalid: true });
}
const res = await fetch('https://api.mailcandor.com/v1/emails', {
method: 'POST',
headers: {
Authorization: `Bearer ${MAILCANDOR_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
from: 'Acme website <hello@acme.com>',
to: 'team@acme.com',
reply_to: email,
subject: 'New contact form message',
text: message
})
});
if (!res.ok) {
const { error } = await res.json();
console.error('email failed', error.type, error.message);
return fail(502, { email, message, failed: true });
}
return { sent: true };
}
} satisfies Actions;
What the code is doing:
fail(400, ...)returns the submitted values so the form can show them again with an error. In SvelteKit 3, enhanced forms receive the status code you pass tofail, not a blanket 200.- The email goes to your team, with the visitor in
reply_to. Nobody can use the form to send mail to arbitrary addresses. - API errors arrive as
{"error": {"type", "message", "field"}}. They are logged on the server and replaced with a plain message for the visitor.
Step 3: build the page
<!-- src/routes/contact/+page.svelte -->
<script lang="ts">
import { enhance } from '$app/forms';
let { form } = $props();
</script>
{#if form?.sent}
<p>Thanks, we will reply soon.</p>
{:else}
<form method="POST" use:enhance>
<label>
Email
<input name="email" type="email" required value={form?.email ?? ''} />
</label>
<label>
Message
<textarea name="message" required>{form?.message ?? ''}</textarea>
</label>
{#if form?.invalid}<p>Please add your email and a message.</p>{/if}
{#if form?.failed}<p>Something went wrong. Please try again.</p>{/if}
<button>Send</button>
</form>
{/if}
Without JavaScript, the browser posts the form and SvelteKit renders the page with the action’s result. With JavaScript, use:enhance submits in the background and updates form without a full reload.
Add bot protection before launch. A hidden honeypot input that real users leave blank, checked in the action, stops most scripted spam; Cloudflare Turnstile or another CAPTCHA stops more.
Sending transactional email from SvelteKit
The same fetch call works in a +server.ts endpoint, a hook, or any module that only the server imports. For sign-up confirmations, receipts and alerts:
- Put the call in one helper so every email shares headers and error handling.
- Send an
Idempotency-Keyheader unique to the email, such asorder-1042-receipt. If the code runs twice, the API returns the first response instead of sending again. - The API replies with 202 and
{"id": "...", "status": "queued"}. Store the id if you want to match delivery webhooks to the email later. - For many recipients,
POST /v1/emails/batchtakes up to 100 emails per request.
What about remote functions?
SvelteKit’s experimental form remote function covers the same use case with more type safety, and the SvelteKit team says new development is focused there. The email code inside it is the same fetch call. Until the feature is stable, form actions are the safer choice for production.
Testing locally
Run npm run dev with the key in .env.local and submit the form to a real inbox you own. Check three things: the email arrives, the subject and sender look right, and pressing reply addresses the visitor, not your own from address. Then submit the form empty and with a bad address to confirm the validation messages appear, both with JavaScript on and with it turned off in your browser’s developer tools. Finally, set an invalid key and confirm the visitor sees the friendly error while the real API error lands in your server log.
Can I use SMTP?
With adapter-node, Nodemailer works in server code; the Node.js guide has the setup for ports 465 and 587. On edge adapters such as Cloudflare, Node’s SMTP stack is not available, so use the API; see sending from Cloudflare Workers. An HTTPS email API runs on every adapter.
Before you send: verify your domain
Mail from a domain without SPF, DKIM and DMARC records is likely to land in spam. Add your domain with your email provider and publish its DNS records. The SPF, DKIM and DMARC setup guide explains each one.
Sending with Mailcandor
The action above works with Mailcandor’s email API as written, with no SDK to install. Access is by request through the pricing page.