Send emails with Next.js
Send a sandbox email from a Next.js App Router Server Action with @messagebird/sdk. You need Node.js 20.9 or later, npm, and a Bird workspace with an API key that can send email. Create the key in Developers > API keys; Send your first email walks through it.
Download the Next.js example for the Server Action, form and setup instructions, or follow the steps below.
1. Install
Ejemplo de código
npx create-next-app@latest my-app --yes --ts --eslint --no-tailwind --app --no-src-dir --use-npm --disable-git
cd my-app
npm install @messagebird/sdkIn the new my-app directory, create .env.local beside package.json:
Ejemplo de código
BIRD_API_KEY=YOUR_API_KEYReplace YOUR_API_KEY with your workspace key. Keep the file out of version control and keep the variable server-only: do not prefix it with NEXT_PUBLIC_. Restart the development server after changing the key.
2. Send
Create app/actions/send-welcome.ts. The "use server" directive keeps it (and your API key) on the server:
Ejemplo de código
"use server";
import { BirdClient } from "@messagebird/sdk";
const bird = new BirdClient({ apiKey: process.env.BIRD_API_KEY! });
export async function sendWelcome() {
const msg = await bird.email.send({
from: "onboarding@messagebird.dev",
to: ["delivered@messagebird.dev"],
subject: "Hello from Bird",
html: "<p>My first Bird email.</p>",
});
console.log(msg.id, msg.status); // "em_…", "accepted"
return { id: msg.id, status: msg.status };
}onboarding@messagebird.dev is the shared onboarding sender. delivered@messagebird.dev simulates successful delivery without delivering to a real inbox. You do not need to verify a domain for this test; onboarding limits still apply. The SDK infers the region from your key's bk_us1_ or bk_eu1_ prefix.
3. Try it
Replace app/page.tsx with this form. Its wrapper awaits sendWelcome without returning the result to the form:
Ejemplo de código
import { sendWelcome } from "./actions/send-welcome";
export default function Home() {
async function submit(): Promise<void> {
"use server";
await sendWelcome();
}
return (
<form action={submit}>
<button type="submit">Send sandbox email</button>
</form>
);
}Run npm run dev, open the local URL printed by Next.js (normally http://localhost:3000), and select Send sandbox email once. The form leaves its result in the server terminal, which logs the em_ ID and accepted status after a successful 202 response:
Ejemplo de código
em_01ky7ma8y2es1s2akzk53tmjn0 acceptedAcceptance precedes the asynchronous recipient outcome. Use that ID in the email log or message events API to check the simulated delivery.
The SDK generates an idempotency key for each call and reuses it for retries within that call. A new form submission normally starts a new operation. For a deliberate retry across calls, retain the operation's key and request, then pass the key through the SDK request options. Completed responses are retained for three hours; after that, the same key can start a new operation. Follow the idempotency guide before retrying an uncertain result.
If the request fails, read the server error before submitting again:
- For 401, check that .env.local contains the intended workspace key and restart the development server. For a permission refusal, check the key's email-send access.
- For 422, correct the field named in the validation error. Keep the onboarding sender and sandbox recipient from this example while testing.
- For a timeout, connection error, or 5xx, acceptance may be unknown. If you have a message ID, inspect its recorded outcome. Without one, reconcile the original attempt in the email log before creating another operation. A missing response does not prove that no email was accepted; response retention does not make side effects atomic.
Keep this unauthenticated form local. Before publishing a real-recipient form, authenticate and authorize the caller inside the Server Action, validate the submitted data, and add abuse controls. The server directive protects the key; it does not grant permission to send. Verify your own sending domain before moving beyond the onboarding sender.
Next steps
- TypeScript email SDK: the full email surface (send, get, list) and the error model.
- Send your first email: creating an API key and the full set of sandbox addresses.
- Sending domains: verify your own domain for production sending.
- Email events: follow recipient outcomes after acceptance.
- Email API reference: the full request and response schema.
Recursos relacionados
Continúa con la documentación, guías y ejemplos sobre este tema. Los recursos están en inglés.
Ver la guíaGetting started with emailComprender el conceptoShould I use a Bird SDK or call the API directly?Explorar la funcionalidadEmailSeguir la ruta de aprendizajeBuild your first integration
Prueba el ejercicio y obtén un resumen de implementación