Skip to content

Documentation

Send email from SvelteKit.

A form action that validates, sends and reports back, with the key kept on the server.

Before you start

You need a verified sending domain (see Domains) and an API key (under API keys in the dashboard; it is shown once). Keep the key in an environment variable on your server, never in code that runs in a browser or an app.

Install

Add the client. It runs in SvelteKit's server code, including on edge adapters.

Terminal
npm install mailtruss

The form action

Keep the key in a private environment variable ($env/static/private), so it cannot reach the browser. The action validates the fields with fail() and sends.

src/routes/contact/+page.server.ts
import { fail } from "@sveltejs/kit";
import { MAILTRUSS_API_KEY } from "$env/static/private";
import { MailClient, MailError } from "mailtruss";
import type { Actions } from "./$types";
​
const mail = new MailClient({ apiKey: MAILTRUSS_API_KEY });
const escapeHtml = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
​
export const actions: Actions = {
default: async ({ request }) => {
const form = await request.formData();
const email = String(form.get("email") ?? "").trim();
const message = String(form.get("message") ?? "").trim();
if (!email.includes("@") || !message) return fail(400, { email, message, error: "Enter your email and a message." });
try {
await mail.emails.send({
from: "Site <hello@yourdomain.com>", to: "you@yourdomain.com", reply_to: email,
subject: "New message from the site", html: `<p>${escapeHtml(message)}</p>`,
});
} catch (e) {
if (e instanceof MailError) return fail(502, { email, message, error: "We could not send that. Try again in a minute." });
throw e;
}
return { success: true };
},
};

The form

A plain form works without JavaScript, and use:enhance adds progressive enhancement.

src/routes/contact/+page.svelte
<script lang="ts">
import { enhance } from "$app/forms";
let { form } = $props();
</script>
​
<form method="POST" use:enhance>
<input name="email" type="email" value={form?.email ?? ""} required />
<textarea name="message" required>{form?.message ?? ""}</textarea>
<button>Send</button>
{#if form?.error}<p role="alert">{form.error}</p>{/if}
{#if form?.success}<p>Sent. Thank you.</p>{/if}
</form>

Try it without sending real mail

Send to delivered@mailtruss.test first. It works before any domain is verified and reaches no real mailbox, so you can check your code and see the recorded timeline. Then try bounced@mailtruss.test to see what a bounce looks like. All the test addresses are listed under Sending.

See what happened

Open the message under Emails in the dashboard: it shows the recorded timeline, what each event proves, and a diagnosis if something went wrong. Or fetch it with GET /api/v1/emails/:id/events. To be told as it happens, add a webhook.

If it fails

API requests answer with an error name and message. The common ones:

  • 403 invalid_api_key or 401 missing_api_key: the key is wrong, revoked or not sent. Send it as Authorization: Bearer ms_live_….
  • 403 domain_not_verified: the from address is on a domain that is not verified. Publish the DNS records and re-check.
  • 422 validation_error: fix the field the message names. Nothing was sent and no quota was used.
  • 429 rate_limit_exceeded: back off for the Retry-After header. See rate limits.

Problems that happen after a message is accepted (bounces, complaints) are explained under delivery errors.

Other guides

Last updated

Something wrong or unclear on this page?

Report an issue