Send email from Express with Shipmail
Send email from an Express route with the shipmail SDK. The example sends an order receipt when your app posts to /orders/:id/receipt.
Last updated
Before you start
- A verified sending subdomain, such as
notify.example.com, with an active sender. See Transactional email. - An API key with send access to the sender's mailbox.
- The sender address, such as
hello@notify.example.com. Use the bare address. Shipmail adds the sender name.
Install the SDK
Add the TypeScript SDK and put the key and the sender address in the server's environment.
npm install shipmailSHIPMAIL_API_KEY=sm_live_...
EMAIL_FROM=hello@notify.example.comAdd the route
The example uses Express 5, which passes errors thrown in an async handler to its error handler. The idempotency key is built from the order id, so a second request for the same order within 24 hours does not send a second receipt. See Idempotency.
// server.ts
import express from "express";
import { RateLimitError, ShipmailClient, ShipmailError } from "shipmail";
const app = express();
app.use(express.json());
const shipmail = new ShipmailClient(process.env.SHIPMAIL_API_KEY!);
app.post("/orders/:id/receipt", async (req, res) => {
const orderId = req.params.id;
try {
const message = await shipmail.messages.send(
{
from: process.env.EMAIL_FROM,
to: [req.body.email],
subject: `Your receipt for order ${orderId}`,
text: "Thanks for your order.",
},
{ idempotencyKey: `receipt-${orderId}` },
);
res.status(201).json({ id: message.id });
} catch (error) {
if (error instanceof RateLimitError) {
res.set("Retry-After", String(error.retryAfter ?? 60));
res.status(503).json({ error: "Try again later" });
} else if (error instanceof ShipmailError) {
console.error(error.requestId, error.message);
res.status(502).json({ error: "Email not sent" });
} else {
throw error;
}
}
});
app.listen(3000);Handle rate limits and errors
With an idempotency key, the SDK retries a 429 or a server error by itself and waits as long as Retry-After asks, up to 60 seconds. If the limit still holds, it throws RateLimitError, and the route answers 503 with the same wait. Any other refusal throws a ShipmailError subclass with the request id to quote to support. See Rate limits.
Test without sending
Use a sm_test_ key while you build. Shipmail accepts the request, delivers nothing and lists the send under Test in Activity. See Sandbox mode.