Send
Send a predefined email using the API route
Send emails using SvelteKit and the MailChannels Node.js SDK.
Add the mailchannels-sdk package dependency to your SvelteKit project.
npm i mailchannels-sdkyarn add mailchannels-sdkpnpm add mailchannels-sdkbun add mailchannels-sdkdeno add npm:mailchannels-sdkAdd your MailChannels API key to your .env file.
MAILCHANNELS_API_KEY=your-api-keyCreate a server API route under src/routes/api/send/+server.ts.
Use the html property to send an email with HTML content.
import { json } from '@sveltejs/kit'
import { MailChannels } from 'mailchannels-sdk'
import { MAILCHANNELS_API_KEY } from '$env/static/private'
import type { RequestHandler } from './$types'
const mailchannels = new MailChannels(MAILCHANNELS_API_KEY)
export const POST: RequestHandler = async () => {
const { data, error } = await mailchannels.emails.send({
from: 'Name <from@example.com>',
to: 'to@example.com',
subject: 'Test email',
html: '<p>Hello World</p>'
})
if (error) {
return json(error, { status: error.statusCode || 400 })
}
return json(data)
}Create a form in your SvelteKit app to call the send API route.
<script lang="ts">
let loading = $state(false)
let result = $state<{ data?: unknown, error?: unknown } | null>(null)
async function handleSubmit (event: SubmitEvent) {
event.preventDefault()
loading = true
result = null
const response = await fetch('/api/send', { method: 'POST' })
result = await response.json()
loading = false
}
</script>
<h1>MailChannels SvelteKit Example</h1>
<form onsubmit={handleSubmit}>
<button type="submit" disabled={loading}>
{loading ? 'Sending...' : 'Send Email'}
</button>
</form>
{#if result}
<pre>{JSON.stringify(result, null, 2)}</pre>
{/if}