Send email from Convex with Shipmail
Convex mutations cannot call the network, so the email goes out from an action. A mutation schedules the action after it writes, and the action calls the Shipmail API.
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.
Set the environment variables
Set them on each deployment, development and production. Functions read them from process.env.
npx convex env set SHIPMAIL_API_KEY sm_live_...
npx convex env set EMAIL_FROM hello@notify.example.comAdd the action
The action uses fetch, so it runs in the default Convex runtime and needs no "use node". It is internal, so clients cannot call it.
// convex/email.ts
import { v } from "convex/values";
import { internalAction } from "./_generated/server";
export const send = internalAction({
args: { to: v.string(), subject: v.string(), text: v.string() },
handler: async (_ctx, { to, subject, text }) => {
const res = await fetch("https://shipmail.to/api/v1/messages", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SHIPMAIL_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ from: process.env.EMAIL_FROM, to: [to], subject, text }),
});
if (!res.ok) throw new Error(`Shipmail returned ${res.status}: ${await res.text()}`);
},
});Schedule it from a mutation
runAfter(0, ...) starts the action only if the mutation commits. If the insert fails, no email goes out.
// convex/users.ts
import { v } from "convex/values";
import { internal } from "./_generated/api";
import { mutation } from "./_generated/server";
export const signUp = mutation({
args: { email: v.string() },
handler: async (ctx, { email }) => {
await ctx.db.insert("users", { email });
await ctx.scheduler.runAfter(0, internal.email.send, {
to: email,
subject: "Welcome to Acme",
text: "Thanks for signing up.",
});
},
});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.