Send with

Send email with Nuxt

Send email from a server route, so the API key never reaches the browser.

Runtime config

// nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    // Private: server only. Set it with NUXT_ROBUSTEMAIL_API_KEY
    robustemailApiKey: "",
  },
});
# .env
NUXT_ROBUSTEMAIL_API_KEY=rb_test_...

A contact form endpoint

// server/api/contact.post.ts
export default defineEventHandler(async (event) => {
  const { name, email, message } = await readBody(event);
  if (!email || !message) {
    throw createError({ statusCode: 400, statusMessage: "Email and message are required" });
  }

  const { robustemailApiKey } = useRuntimeConfig(event);

  const result = await $fetch<{ id: string }>("https://robustemail.com/api/v2/emails", {
    method: "POST",
    headers: { Authorization: `Bearer ${robustemailApiKey}` },
    body: {
      from: "Acme Website <website@acme.com>",
      to: "team@acme.com",
      reply_to: email,
      subject: `New message from ${name || email}`,
      text: String(message),
    },
  }).catch((err) => {
    // err.data holds the API's { name, message }
    console.error("Email failed", err.data);
    throw createError({ statusCode: 502, statusMessage: "We could not send your message" });
  });

  return { ok: true, id: result.id };
});

$fetch sends the object as JSON and throws on 4xx and 5xx responses.

Call it from a page

<script setup lang="ts">
const form = reactive({ name: "", email: "", message: "" });
const sent = ref(false);

async function submit() {
  await $fetch("/api/contact", { method: "POST", body: form });
  sent.value = true;
}
</script>

<template>
  <p v-if="sent">Thanks, we will reply soon.</p>
  <form v-else @submit.prevent="submit">
    <input v-model="form.name" placeholder="Name" />
    <input v-model="form.email" type="email" placeholder="Email" required />
    <textarea v-model="form.message" required />
    <button>Send</button>
  </form>
</template>

The email comes from your own domain with the visitor in reply_to, so pressing Reply answers them.

Next