To send email from Astro, define an Astro Action that accepts your form, validates it with Zod, and calls an email provider’s HTTP API (or SMTP through Nodemailer on a Node server) from the action’s handler, with the API key kept server-side in astro:env. The action needs an adapter because it runs on the server, and the page with the form either renders on request or calls the action from a small script.
This guide builds a contact form that sends email end to end: config, the action, the form, spam protection, error handling and the choices that differ by host.
Key Takeaways
- Email is sent from the action handler, never from browser code, so the API key never reaches the client.
- Declare the key with
envField.string({ context: 'server', access: 'secret' })and import it fromastro:env/server.- On serverless and edge hosts, use an email provider’s HTTP API; SMTP needs a long-running Node server.
- Send from your own verified domain and put the visitor’s address in
reply_to.- Add a honeypot field and rate limiting before you go live.
What you need before writing code
Three things have to be in place:
- An adapter. Actions run on the server, so the project needs
@astrojs/node,@astrojs/netlify,@astrojs/vercelor@astrojs/cloudflare. Install one withnpx astro add node(or your host’s name). - An email provider. Transactional providers such as Resend, Postmark, SendGrid, Mailgun and Amazon SES all accept a JSON request and send the message. Your own mail server over SMTP also works if you run Node.
- A verified sending domain. Providers require you to add DNS records (SPF and DKIM, usually DMARC too) for the domain in your
fromaddress. Without them, mail lands in spam or is rejected.
If you’d rather not run any server code, a hosted form backend can send the email for you from a static site. Our comparison of form backends for static Astro sites covers that route, and the guide to contact forms on a static Astro site shows the HTML side.
Declare the secrets with astro:env
Keep the API key and addresses in a typed schema so a missing value fails the build instead of a live form:
// astro.config.mjs
import { defineConfig, envField } from 'astro/config';
import node from '@astrojs/node';
export default defineConfig({
adapter: node({ mode: 'standalone' }),
env: {
schema: {
RESEND_API_KEY: envField.string({ context: 'server', access: 'secret' }),
CONTACT_TO: envField.string({ context: 'server', access: 'secret' }),
CONTACT_FROM: envField.string({ context: 'server', access: 'public' }),
},
},
});
Put the values in .env locally and in your host’s environment settings for production:
# .env
RESEND_API_KEY=re_your_key_here
CONTACT_TO=[email protected]
CONTACT_FROM="Example Site <[email protected]>"
Secrets declared with access: 'secret' are read at runtime and can only be imported in server code. If a client script tries to import them, the build fails. The environment variables guide explains the schema options in full.
The send-email action
The action validates the form, builds a plain-text message and posts it to the provider. This example uses Resend’s REST API with fetch, so there is no SDK to install and it runs on every adapter:
// src/actions/index.ts
import { defineAction, ActionError } from 'astro:actions';
import { z } from 'astro/zod';
import { RESEND_API_KEY, CONTACT_TO, CONTACT_FROM } from 'astro:env/server';
export const server = {
contact: defineAction({
accept: 'form',
input: z.object({
name: z.string().trim().min(1, 'Please add your name').max(100),
email: z.email('Please enter a valid email'),
message: z.string().trim().min(10, 'A little more detail, please').max(5000),
website: z.string().max(0).optional(), // honeypot: humans leave it empty
}),
handler: async ({ name, email, message }) => {
const res = await fetch('https://api.resend.com/emails', {
method: 'POST',
headers: {
Authorization: `Bearer ${RESEND_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
from: CONTACT_FROM,
to: [CONTACT_TO],
reply_to: email,
subject: `New message from ${name}`,
text: `From: ${name} <${email}>\n\n${message}`,
}),
});
if (!res.ok) {
console.error('Email send failed', res.status, await res.text());
throw new ActionError({
code: 'INTERNAL_SERVER_ERROR',
message: 'We could not send your message. Please try again or email us directly.',
});
}
return { sent: true };
},
}),
};
Some details that matter:
fromis always your address. Never put the visitor’s email infrom; providers reject it and receiving servers flag it as spoofing. The visitor goes inreply_to, so pressing Reply in your inbox answers them.- Plain text first. A contact notification doesn’t need HTML. If you add an
htmlversion, escape every user value before inserting it, or someone can inject markup into your inbox. - Log the provider’s error, show a generic one. The visitor doesn’t need the provider’s response body, but you do.
Swapping providers only changes the fetch call: Postmark, SendGrid and Mailgun each take a similar JSON body with their own field names. Check the provider’s API reference for the exact shape.
The form and the result
Call the action straight from an HTML form. It works without JavaScript, and Astro renders the page again with the result:
---
// src/pages/contact.astro
import { actions, isInputError } from 'astro:actions';
import BaseLayout from '../layouts/BaseLayout.astro';
export const prerender = false;
const result = Astro.getActionResult(actions.contact);
const fieldErrors = result?.error && isInputError(result.error) ? result.error.fields : {};
---
<BaseLayout title="Contact">
{result?.data?.sent ? (
<p role="status">Thanks, your message is on its way. We reply within two working days.</p>
) : (
<form method="POST" action={actions.contact}>
<label>Name <input name="name" required autocomplete="name" /></label>
{fieldErrors.name && <p class="error">{fieldErrors.name.join(', ')}</p>}
<label>Email <input name="email" type="email" required autocomplete="email" /></label>
{fieldErrors.email && <p class="error">{fieldErrors.email.join(', ')}</p>}
<label>Message <textarea name="message" rows="6" required></textarea></label>
{fieldErrors.message && <p class="error">{fieldErrors.message.join(', ')}</p>}
<div hidden aria-hidden="true">
<label>Website <input name="website" tabindex="-1" autocomplete="off" /></label>
</div>
{result?.error && !isInputError(result.error) && (
<p class="error" role="alert">{result.error.message}</p>
)}
<button type="submit">Send message</button>
</form>
)}
</BaseLayout>
Field errors come from the Zod messages in the schema, so the wording lives in one place. The required and type="email" attributes catch most mistakes in the browser before the request is made.
Calling the action without a page reload
If the page should stay static, keep prerender on and submit from a script instead:
<!-- src/components/ContactForm.astro -->
<form id="contact">
<!-- same fields as above -->
<button type="submit">Send message</button>
<p id="contact-status" role="status"></p>
</form>
<script>
import { actions } from 'astro:actions';
const form = document.querySelector<HTMLFormElement>('#contact')!;
const status = document.querySelector('#contact-status')!;
form.addEventListener('submit', async (event) => {
event.preventDefault();
const { error } = await actions.contact(new FormData(form));
status.textContent = error ? error.message : 'Thanks, your message is on its way.';
if (!error) form.reset();
});
</script>
The page builds to HTML, and only the action endpoint runs on the server. The Astro Actions guide covers the post-redirect-get pattern if you want a refresh-safe server-rendered version.
Stop spam before it reaches your inbox
A public form that sends email will be found by bots within days. Layer these defences:
- Honeypot field. The hidden
websiteinput above must be empty. Bots that fill every field fail validation, and you never call the provider. - Rate limiting. Limit submissions per IP in middleware or at the host. Cloudflare, Netlify and Vercel all offer rate-limit rules; a counter in a session or a small key-value store works too.
- A challenge for busy forms. If spam gets past the first two, add Cloudflare Turnstile or hCaptcha and verify the token inside the handler before sending.
- Length limits. The
max()rules in the schema stop someone posting megabytes of text.
Never send an automatic confirmation email to the address someone typed. Spammers use that to deliver messages through your domain, and your sending reputation pays for it.
SMTP with Nodemailer on a Node server
If you deploy with @astrojs/node to a server you control, you can send through any SMTP account with Nodemailer:
// src/lib/mailer.ts
import nodemailer from 'nodemailer';
import { SMTP_HOST, SMTP_USER, SMTP_PASS } from 'astro:env/server';
export const mailer = nodemailer.createTransport({
host: SMTP_HOST,
port: 587,
secure: false, // STARTTLS on port 587
auth: { user: SMTP_USER, pass: SMTP_PASS },
});
Then in the handler, replace the fetch call with await mailer.sendMail({ from, to, replyTo: email, subject, text }). Declare the three SMTP variables in the env.schema as before.
SMTP is the wrong fit for serverless and edge hosts. Each invocation opens a new connection, some platforms block outbound SMTP ports, and the Cloudflare Workers runtime doesn’t support Nodemailer. Use an HTTP API there.
Which approach fits your host
| Host and adapter | Recommended way to send | Notes |
|---|---|---|
Node server (@astrojs/node) |
SMTP or HTTP API | Reuse one transport; both work |
Vercel (@astrojs/vercel) |
HTTP API | Functions are short-lived |
Netlify (@astrojs/netlify) |
HTTP API | Same as Vercel |
Cloudflare (@astrojs/cloudflare) |
HTTP API | No Nodemailer in Workers |
| Static only, no adapter | Hosted form backend | No server code at all |
Test it before launch
- Submit the form with each field empty and with a bad email, and check the messages.
- Fill in the honeypot from the browser console and confirm nothing is sent.
- Revoke the API key temporarily and confirm the visitor sees the friendly error and your logs show the provider’s reply.
- Send to a Gmail and an Outlook address and check that the message isn’t in spam, and that the provider shows DKIM as passing.
Every Komal theme builds to static files, and contact forms in our Astro themes need a destination before launch. Adding an adapter and this action is one way to provide it; the Astro config docs show where the adapter and env settings go. The official Actions reference has the full API.
FAQ
Can Astro send emails?
Yes, from server code. Add an adapter, then send from an Astro Action, an API endpoint or middleware using an email provider’s HTTP API or SMTP. A fully static Astro site can’t send email on its own and needs a form backend instead.
How do I send email from an Astro contact form?
Create an action with defineAction({ accept: 'form', input, handler }), validate the fields with Zod, call your email provider inside the handler, and set the form’s action to actions.contact. Keep the API key in astro:env/server.
Can I use Nodemailer with Astro?
Yes, when you deploy with the Node adapter to a long-running server. Nodemailer doesn’t work in the Cloudflare Workers runtime, and SMTP is a poor fit for short-lived serverless functions, so use an HTTP email API on those hosts.
Why are my Astro form emails going to spam?
Usually because the sending domain isn’t verified. Add the SPF and DKIM records your provider gives you, set a DMARC policy, send from your own domain rather than the visitor’s address, and put the visitor in reply_to.
Do Astro Actions work on a static site?
The action itself always runs on the server, so you need an adapter. The page holding the form can stay prerendered if it calls the action from a client script instead of a plain form post.