unsent
unsent.dev
Guides

SvelteKit

How to send emails with Unsent in SvelteKit

Introduction

This guide shows how to send emails using Unsent in a SvelteKit application using Form Actions.

Install dependencies

npm install @unsent/sdk
pnpm add @unsent/sdk
yarn add @unsent/sdk
bun add @unsent/sdk

Configure API Key

Add your Unsent API key to your environment variables file (.env).

.env
UNSENT_API_KEY=un_...

Create Form Action

Create a form action in src/routes/+page.server.ts.

src/routes/+page.server.ts
import { Unsent } from '@unsent/sdk';
import { UNSENT_API_KEY } from '$env/static/private';

const unsent = new Unsent(UNSENT_API_KEY);

export const actions = {
  default: async ({ request }) => {
    const formData = await request.formData();
    const email = formData.get('email') as string;

    const { data, error } = await unsent.emails.send({
      from: 'Acme <onboarding@unsent.dev>',
      to: [email],
      subject: 'Hello world',
      html: '<strong>It works!</strong>',
    });

    if (error) {
      return { success: false, error };
    }

    return { success: true, data };
  }
};

Create Form

Create a form in src/routes/+page.svelte.

src/routes/+page.svelte
<script>
  export let form;
</script>

<form method="POST">
  <input type="email" name="email" required placeholder="Enter your email" />
  <button type="submit">Send Email</button>
</form>

{#if form?.success}
  <p>Email sent successfully!</p>
{/if}