Guides
Nuxt
How to send emails with Unsent in Nuxt
Introduction
This guide shows how to send emails using Unsent in a Nuxt application using Server Routes.
Install dependencies
npm install @unsent/sdkpnpm add @unsent/sdkyarn add @unsent/sdkbun add @unsent/sdkConfigure API Key
Add your Unsent API key to your .env file.
UNSENT_API_KEY=un_...And configure it in nuxt.config.ts.
export default defineNuxtConfig({
runtimeConfig: {
unsentApiKey: process.env.UNSENT_API_KEY,
},
});Create Server Route
Create a server route in server/api/send.post.ts.
import { Unsent } from '@unsent/sdk';
const config = useRuntimeConfig();
const unsent = new Unsent(config.unsentApiKey);
export default defineEventHandler(async (event) => {
const body = await readBody(event);
const { email } = body;
const { data, error } = await unsent.emails.send({
from: 'Acme <onboarding@unsent.dev>',
to: [email],
subject: 'Hello world',
html: '<strong>It works!</strong>',
});
if (error) {
throw createError({
statusCode: 500,
statusMessage: error.message,
});
}
return data;
});Call API
Call the API from your Vue component.
<script setup>
async function sendEmail() {
await $fetch('/api/send', {
method: 'POST',
body: { email: 'delivered@unsent.dev' }
});
alert('Email sent!');
}
</script>
<template>
<button @click="sendEmail">Send Email</button>
</template>