Quickstarts
Send with Astro
Send email from an Astro endpoint or action with the usend SDK.
Astro needs server rendering (an adapter, or output: 'server') for endpoints that run on request. You need a verified domain and an API key.
1. Install
npm install @usend/nodeUSEND_API_KEY=us_1234567892. API endpoint
import type { APIRoute } from 'astro';
import { Usend } from '@usend/node';
export const prerender = false;
const usend = new Usend(import.meta.env.USEND_API_KEY);
export const POST: APIRoute = async ({ request }) => {
const { email, message } = await request.json();
const { data, error } = await usend.emails.send({
from: 'Acme <[email protected]>',
to: ['[email protected]'],
reply_to: email,
subject: 'Contact form',
text: message,
});
if (error) {
return new Response(JSON.stringify({ error }), { status: 502 });
}
return new Response(JSON.stringify({ id: data.id }), {
headers: { 'Content-Type': 'application/json' },
});
};Variables without the PUBLIC_ prefix stay on the server.
3. Call it from a page
<form id="contact">
<input name="email" type="email" required />
<textarea name="message" required></textarea>
<button>Send</button>
</form>
<script>
document.getElementById('contact')!.addEventListener('submit', async (e) => {
e.preventDefault();
const data = Object.fromEntries(new FormData(e.target as HTMLFormElement));
const res = await fetch('/api/send', { method: 'POST', body: JSON.stringify(data) });
alert(res.ok ? 'Sent' : 'Something went wrong');
});
</script>Keep the from address fixed on your verified domain. Next: Send emails.