Send with

Send email with Astro

Astro Actions run on the server and validate their input, which makes them a good home for sending email. Actions need on-demand rendering, so add an adapter (Node, Vercel, Netlify or Cloudflare) to your project.

Environment

# .env
ROBUSTEMAIL_API_KEY=rb_test_...

Variables without the PUBLIC_ prefix are only available on the server.

The action

// src/actions/index.ts
import { ActionError, defineAction } from "astro:actions";
import { z } from "astro:schema";

export const server = {
  contact: defineAction({
    accept: "form",
    input: z.object({
      email: z.string().email(),
      message: z.string().min(1).max(5000),
    }),
    handler: async ({ email, message }) => {
      const res = await fetch("https://robustemail.com/api/v2/emails", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${import.meta.env.ROBUSTEMAIL_API_KEY}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          from: "Acme Website <website@acme.com>",
          to: "team@acme.com",
          reply_to: email,
          subject: "New contact form message",
          text: message,
        }),
      });

      const body = await res.json();
      if (!res.ok) {
        console.error("Email failed", body.name, body.message);
        throw new ActionError({ code: "INTERNAL_SERVER_ERROR", message: "We could not send your message." });
      }
      return { id: body.id as string };
    },
  }),
};

The page

---
// src/pages/contact.astro
import { actions } from "astro:actions";

export const prerender = false;
const result = Astro.getActionResult(actions.contact);
---
{result && !result.error
  ? <p>Thanks, we will reply soon.</p>
  : <form method="POST" action={actions.contact}>
      <input name="email" type="email" required />
      <textarea name="message" required></textarea>
      {result?.error && <p>{result.error.message}</p>}
      <button>Send</button>
    </form>}

The form posts straight to the action, so it works without any client-side JavaScript.

Next