How to Send Email from Bun: SMTP, APIs and bun test
Send email from Bun with Nodemailer over SMTP, a provider's HTTP API through fetch, or Email SDK with a fallback provider, then test it with bun test.
To send email from Bun, call an email provider’s HTTP API with Bun’s built-in fetch, or install Nodemailer and send over SMTP. Bun has no email API of its own, but it runs Nodemailer and provider SDKs, and it reads API keys from .env files without dotenv.
This guide shows working TypeScript for three approaches, a Bun.serve route that sends a welcome email, and a bun test that checks the email without sending one. Every sample ran on Bun 1.4.4 on 2026-11-29 with @opencoredev/email-sdk 3.1.0 and Nodemailer 10.6. The SMTP samples sent to a local Mailpit inbox and the HTTP samples ran against a stubbed fetch, so no real email went out. To start with Email SDK right away, the install guide has the bun add command and a minimal Bun example.
Which way to send email from Bun
| SMTP with Nodemailer | Provider HTTP API with fetch |
Email SDK | |
|---|---|---|---|
| Install | bun add nodemailer |
Nothing | bun add @opencoredev/email-sdk |
| Works with | Any SMTP server | One provider | 26 provider APIs plus SMTP |
| Switching providers | Change SMTP settings | Rewrite the request | Change the adapter |
| Fallback provider | Write it yourself | Write it yourself | Built in, opt-in |
| Tests without sending | Mailpit or Nodemailer test transports | Stub fetch |
memoryAdapter with bun test |
Send from the server only. An API key or SMTP password that ends up in a browser bundle lets anyone send mail from your domain. Verify your sending domain with your provider first; the email DNS checker shows whether SPF, DKIM and DMARC resolve.
Send email over SMTP with Nodemailer
Nodemailer works on Bun as it does on Node.js, because Bun implements the node:net and node:tls modules it uses. Install it with its types:
bun add nodemailer
bun add -d @types/nodemailer
Put your SMTP settings in .env. Bun reads .env files before your code runs, so process.env and Bun.env already hold these values. A plain bun run also reads .env.local; bun test reads .env.test instead and skips .env.local. Bun’s environment variable docs list every file and the order they apply in.
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=apikey
SMTP_PASS=your-smtp-password
import nodemailer from "nodemailer";
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT ?? 587),
secure: false,
requireTLS: true,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
});
const info = await transporter.sendMail({
from: "Acme <hello@acme.com>",
to: "user@example.com",
subject: "Hello from Bun",
text: "Sent over SMTP with Nodemailer.",
});
console.log(info.messageId);
Replace from with an address your SMTP server lets you send from and to with an inbox you can read, then run it:
bun send-smtp.ts
Port 587 with secure: false connects in plain text and upgrades with STARTTLS, and requireTLS: true makes Nodemailer refuse to send the password if the upgrade fails. Use port 465 with secure: true for TLS from the first byte. Bun runs top-level await in this TypeScript file, so the script needs no wrapper function. A local Mailpit inbox has no TLS and no login by default, so point a test run at it without auth and with requireTLS: false. Our test ran this script against Mailpit started with --smtp-auth-accept-any --smtp-auth-allow-insecure, with requireTLS: false and dummy credentials. Never turn off requireTLS for a real SMTP server.
Send email with a provider API and fetch
Most email providers take a JSON POST, and Bun’s fetch sends it with no package at all. This example uses the Resend API. Other providers change the URL and the field names, and some change more: Mailgun takes form data instead of JSON, and SendGrid answers a successful send with an empty body and puts the message id in the X-Message-Id header. The SendGrid and Mailgun guides show those requests.
Add the key to .env, replace the sample sender with an address on a domain you verified in Resend, and replace to with an inbox you can read:
RESEND_API_KEY=re_your_api_key
const response = await fetch("https://api.resend.com/emails", {
method: "POST",
headers: {
Authorization: `Bearer ${Bun.env.RESEND_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
from: "Acme <hello@acme.com>",
to: ["user@example.com"],
subject: "Hello from Bun",
text: "Sent with the Resend API and fetch.",
}),
});
if (!response.ok) {
throw new Error(`Resend returned ${response.status}: ${await response.text()}`);
}
const { id } = (await response.json()) as { id: string };
console.log(id);
Run it with bun send-fetch.ts. Check response.ok yourself: fetch resolves on a 401 or a 422 just as it does on a 200. The Resend API guide covers attachments, idempotency keys and Resend’s error codes.
Send email from Bun with Email SDK
Email SDK wraps SMTP and 26 provider APIs behind one send() call, so the code that sends stays the same when you change providers. It runs on Bun 1.1 and later with no extra setup. This client sends through Resend and falls back to SMTP when Resend rejects the request:
bun add @opencoredev/email-sdk
import { createEmailClient } from "@opencoredev/email-sdk";
import { resend } from "@opencoredev/email-sdk/resend";
import { smtp } from "@opencoredev/email-sdk/smtp";
export const email = createEmailClient({
adapters: [
resend({ apiKey: Bun.env.RESEND_API_KEY! }),
smtp({
host: Bun.env.SMTP_HOST!,
port: Number(Bun.env.SMTP_PORT ?? 587),
auth: { user: Bun.env.SMTP_USER!, pass: Bun.env.SMTP_PASS! },
}),
],
defaultAdapter: "resend",
fallback: { adapters: ["smtp"] },
});
import { email } from "./email";
const result = await email.send({
from: "Acme <hello@acme.com>",
to: "user@example.com",
subject: "Hello from Bun",
text: "Sent with Email SDK.",
});
console.log(result.adapter, result.id);
Replace the sender with an address on your verified domain and the recipient with an inbox you can read, here and in the route below, then run it with bun send-sdk.ts. It prints resend and the Resend email id. When the stubbed Resend API answered 401, the same script printed smtp and the message arrived in Mailpit instead (that local run used the Mailpit flags above and set requireTLS: false on the SMTP adapter, because Mailpit has no TLS). Fallback runs by default only when the SDK can prove Resend did not accept the message, such as a 401 or 422 with no earlier timeout or 5xx on the same send. After a timeout or a 5xx the client stops and throws, because the first provider may already have sent the email; retries and provider fallback shows how to opt in and what that risks. On port 587 with auth set, the SMTP adapter upgrades the connection with STARTTLS before it sends the password and throws if the server can’t; port 465 uses TLS from the first byte.
How do I send an email from a Bun.serve route?
Put the send in a function, then call it from a route handler that checks the caller first. Bun.serve with routes needs Bun 1.2.3 or later.
- Create the client once in
email.ts, as above, so every request reuses it. - Write the send as a function that takes the client, so tests can pass a different one.
- Add a
POSTroute that checks an API token in constant time and validates the recipient, then awaits the send and returns the email id.
import type { EmailClient } from "@opencoredev/email-sdk";
export async function sendWelcome(email: EmailClient, to: string) {
return email.send({
from: "Acme <hello@acme.com>",
to,
subject: "Welcome to Acme",
text: "Your account is ready.",
});
}
import { timingSafeEqual } from "node:crypto";
import { EmailValidationError } from "@opencoredev/email-sdk";
import { email } from "./email";
import { sendWelcome } from "./welcome";
const token = Bun.env.INTERNAL_API_TOKEN;
if (!token) throw new Error("Set INTERNAL_API_TOKEN before starting the server");
const expected = Buffer.from(`Bearer ${token}`);
function isAuthorized(request: Request) {
const given = Buffer.from(request.headers.get("authorization") ?? "");
return given.length === expected.length && timingSafeEqual(given, expected);
}
Bun.serve({
hostname: "127.0.0.1",
port: 3000,
routes: {
"/api/welcome": {
POST: async (request) => {
if (!isAuthorized(request)) {
return new Response("Unauthorized", { status: 401 });
}
let body: unknown;
try {
body = await request.json();
} catch {
return new Response("Invalid JSON", { status: 400 });
}
const to = typeof body === "object" && body !== null && "to" in body ? body.to : undefined;
if (typeof to !== "string" || !/^[^@\s,;<>"]+@[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+$/.test(to)) {
return new Response("Invalid recipient", { status: 400 });
}
try {
const result = await sendWelcome(email, to);
return Response.json({ id: result.id });
} catch (error) {
if (error instanceof EmailValidationError) {
return new Response("Invalid message", { status: 400 });
}
throw error;
}
},
},
},
});
Generate a token, export it, and start the server:
export INTERNAL_API_TOKEN="$(openssl rand -hex 32)"
bun server.ts
Then, in a second terminal with the same INTERNAL_API_TOKEN exported:
curl -X POST localhost:3000/api/welcome \
-H "authorization: Bearer $INTERNAL_API_TOKEN" \
-H "content-type: application/json" \
-d '{"to":"user@example.com"}'
Bun binds to every network interface unless you set hostname, so the example listens on 127.0.0.1 only. Before you expose a route like this, replace the shared token with your app’s own auth and decide who may receive mail, or anyone who finds it can send email from your domain.
Test email sending with bun test
Pass sendWelcome a client built on memoryAdapter() instead of the real one. The memory adapter keeps every message and never calls a provider, and the test covers the same function the route calls.
import { expect, test } from "bun:test";
import { createEmailClient } from "@opencoredev/email-sdk";
import { memoryAdapter } from "@opencoredev/email-sdk/testing";
import { sendWelcome } from "./welcome";
test("sends the welcome email", async () => {
const memory = memoryAdapter();
const email = createEmailClient({ adapters: [memory], telemetry: false });
await sendWelcome(email, "user@example.com");
expect(memory.raw?.sent).toHaveLength(1);
expect(memory.raw?.sent[0]?.message.subject).toBe("Welcome to Acme");
});
bun test runs it in milliseconds with no network. Test email sending without sending real email shows how to test retries and fallback the same way, and the Mailpit guide covers checking the rendered message over SMTP.
Which one should you use?
Use fetch with one provider’s API for a small app that will stay on that provider. Use Nodemailer when you already have SMTP credentials or need a server that isn’t an email API. Use Email SDK when you want to switch providers without rewriting send code, add a fallback provider, or test sends with bun test instead of mocking fetch.
FAQ
Does Bun have a built-in way to send email?
No. Bun has no SMTP client or email API of its own. It gives you fetch for provider HTTP APIs and runs Nodemailer for SMTP.
Does Nodemailer work with Bun?
Yes. In our test Nodemailer 10.6 authenticated and sent a message to a local Mailpit inbox on Bun 1.4.4, with the same code that runs on Node.js.
Do I need dotenv in Bun?
No. Bun reads .env files on startup (bun test reads .env.test and skips .env.local), so Bun.env.RESEND_API_KEY and process.env.RESEND_API_KEY work without an import.
Can I send email from Bun in the browser?
No. Send from server code only, such as a Bun.serve route. A key in client code can be read by anyone and used to send mail as you.
Related
- How to send email from Node.js and TypeScript: the same three approaches on Node.js.
- Resend API guide for Node.js and TypeScript: the Resend endpoint, idempotency and errors.
- MailHog and Mailpit: a local SMTP inbox for checking messages.
- Resend adapter: options and supported fields for Resend in Email SDK.