Email setup (Mailgun)
ShipSaaS uses Mailgun to send transactional email: welcome messages, password resets, magic links, and receipts. This guide walks through configuring Mailgun, then adding the four DNS records that prove your domain is yours.
1. Create a Mailgun account
- Sign up at mailgun.com and add a custom sending domain (e.g.
mg.yourdomain.com). - In the Mailgun dashboard, copy the four DNS records shown on the domain-setup page. You will need them in step 3.
- Generate an API key under Settings → API Keys and keep it handy.
2. Configure environment variables
Copy .env.example to .env.local and fill in:
MAILGUN_API_KEY=key-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx MAILGUN_DOMAIN=mg.yourdomain.com MAILGUN_SUBDOMAIN=mg MAILGUN_FROM_NOREPLY="Your App <noreply@mg.yourdomain.com>" MAILGUN_FROM_ADMIN="Your App <admin@mg.yourdomain.com>" MAILGUN_SUPPORT_EMAIL=support@yourdomain.com MAILGUN_FORWARD_TO=hello@yourdomain.com MAILGUN_WEBHOOK_SIGNING_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
3. Add the four DNS records
SPF, DKIM, and DMARC are important deliverability signals. Mailgun provides the exact records for your domain; this template documents the setup but cannot create DNS records or guarantee inbox placement.
SPF (TXT record on the subdomain)
Host: mg.yourdomain.com Type: TXT Value: v=spf1 include:mailgun.org ~all
DKIM (TXT record Mailgun gives you)
Host: pic._domainkey.mg.yourdomain.com Type: TXT Value: k=rsa; p=MIGfMA0GCSq... (long string from Mailgun)
DMARC (TXT record on the apex domain)
Host: _dmarc.yourdomain.com Type: TXT Value: v=DMARC1; p=quarantine; rua=mailto:dmarc@yourdomain.com; pct=100
MX (so bounces get reported back to Mailgun)
Host: mg.yourdomain.com
Type: MX
Value: 10 mxa.mailgun.org
10 mxb.mailgun.org4. Verify in Mailgun
Go back to the Mailgun dashboard. After DNS propagates (usually 5–30 minutes, occasionally up to 24 hours), Mailgun will show all four records as verified. Click Send a test email to confirm.
5. Inbound email (optional)
If you want support@yourdomain.com to forward to your personal inbox, add a Mailgun route that points to MAILGUN_FORWARD_TO and set the webhook URL on your Mailgun domain to:
https://yourdomain.com/api/mailgun/webhook
Testing locally
Use the Mailgun sandbox domain for development so you don't burn your production sending quota. The sandbox only delivers to verified recipients, which is perfect for local testing.
Templates
Ten transactional templates ship with the template. They live in src/lib/email-templates.ts and pull their brand styling (logo, colors, support address) from src/config/email.ts so you can rebrand every outgoing email by editing env vars — no code changes required.
- Welcome — sent by Better Auth's user-create hook in
src/lib/auth.tson user signup. - Email verification — sent automatically on sign-up (
emailVerification.sendOnSignUpinsrc/lib/auth.ts) with theEmailTemplates.emailVerification()template. Resending is built into the sign-in form for unverified accounts. - Sign-in link — the magic-link email. Delivered by the
magicLinkplugin viasendMagicLinkEmail()usingEmailTemplates.magicLink(). - Password reset — the user-facing form lives at
/auth/forgot-passwordand/auth/reset-password. Better Auth callssendPasswordResetEmail()(configured asemailAndPassword.sendResetPassword) which uses theEmailTemplates.passwordReset()template. - Subscription receipt — sent automatically by
src/lib/webhooks/stripe-handler.tsoninvoice.payment_succeededand by the LemonSqueezy handler onsubscription_payment_success. - Payment failed — sent automatically on
invoice.payment_failed(Stripe) andsubscription_payment_failed(LemonSqueezy) with a link back to/dashboard/billingto update the payment method. - Subscription renewal upcoming — sent on Stripe
invoice.upcoming(Stripe sends this ~3 days before the charge). Gives the user a heads-up so they aren't surprised. - Trial ending — sent on Stripe
customer.subscription.trial_will_end(~3 days before the trial ends). Tells the user what happens next. - Refund issued — sent on Stripe
charge.refundedand LemonSqueezyorder_refunded. Confirms the refund and gives a realistic timeline. - Subscription cancelled — sent on Stripe
customer.subscription.deletedand LemonSqueezysubscription_cancelled. Confirms the cancellation, end date, and how to reactivate. - Generic notification —
sendNotificationEmail()is your hook for any one-off email: comment notifications, weekly digests, product updates. Includes a one-click unsubscribe header (RFC 8058) by default.
Set SKIP_EMAILS=true in .env.local to short-circuit Mailgun and log outgoing messages to the console during local development.
Dev preview & test send
Run the dev server and visit /dev/emails to see every template rendered with sample data in your browser. The route is 404'd in production.
To send a real email to yourself and confirm end-to-end deliverability:
# Welcome email npm run email:test -- welcome you@you.com # Payment-failed email npm run email:test -- paymentFailed you@you.com # Dry-run (logs only, no Mailgun call) SKIP_EMAILS=true npm run email:test -- welcome
Email log
Every send writes a row to email_log (table created by migrations/003_email_log.sql) with the recipient, template, Mailgun message id, and tags. Use it to:
- Audit what was sent to a user (ops + GDPR/CCPA data export)
- Track delivery status — the Mailgun webhook updates each row as events arrive (
delivered,bounced,complained,unsubscribed,failed). - Replay a failed email by re-fetching the log row + template.
Unsubscribes
sendNotificationEmail() automatically adds the List-Unsubscribe + List-Unsubscribe-Post headers (RFC 8058). The link points to POST /api/unsubscribe (one-click, no UI) and GET /api/unsubscribe (fallback, shows a confirmation page).
Per Gmail/Outlook bulk sender guidelines, transactional emails are never tagged as unsubscribe-able: receipts, payment-failed notices, password resets, and refunds always go out regardless. The unsubscribe only suppresses marketing and notification sends.
Swapping the provider
All sends go through sendEmail() in src/lib/mailgun.ts. To swap to Resend, Postmark, or AWS SES:
- Install the SDK (
npm i resend, etc.) - Replace the
getMailgunClient()+client.messages.create()call insidesendEmail()with the new provider's API. - Update the inbound webhook in
src/app/api/mailgun/webhook/route.tsto handle the new provider's delivery event format (Resend usesemail.delivered,email.bounced, etc). - The
email_logtable, templates, brand config, and all callers stay unchanged.