Welcome email for new users
Send a welcome email whenever a user is created, with a database trigger, nodemailer and secrets.
Spica's mailer only sends Passport's verification messages. For your own emails, call your provider from a function. This recipe sends a welcome email every time a user is created, however the user was created.
1. Store the SMTP credentials
Create these secrets: SMTP_HOST, SMTP_USER, SMTP_PASS, and an environment variable MAIL_FROM.
2. The function
function/welcome-email/schema.yaml
name: welcome-email
description: Sends a welcome email to new users
language: javascript
timeout: 30
triggers:
onUserCreated:
type: database
active: true
options:
collection: user
type: INSERT
env_vars: [<MAIL_FROM id>]
secrets: [<SMTP_HOST id>, <SMTP_USER id>, <SMTP_PASS id>]function/welcome-email/package.json
{"name": "welcome-email", "version": "0.0.1", "dependencies": {"nodemailer": "^6.9.0"}}function/welcome-email/index.mjs
import nodemailer from "nodemailer";
const transport = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: 587,
auth: {user: process.env.SMTP_USER, pass: process.env.SMTP_PASS}
});
export async function onUserCreated(change) {
const email = change.document?.username;
if (!email?.includes("@")) {
return;
}
await transport.sendMail({
from: process.env.MAIL_FROM,
to: email,
subject: "Welcome to Acme",
text: "Thanks for signing up! Reply to this email if you need anything."
});
console.info("Welcome email sent", change.documentKey);
}The trigger receives the new user document. In this example usernames are email addresses, as in the sign-up recipe.
Why a database trigger?
Users live in Spica's user collection, not in a bucket, so the database trigger is the way to react to them. It fires for users created by your sign-up function, by OAuth logins and by the panel alike.
Make it robust
- Idempotency. Record sent emails (for example in a
Sent emailsbucket keyed by user id) and skip users who already got one. - Failures. Log errors with
console.errorand the user id, and filter on them in the logs. - Providers with HTTP APIs. Replace nodemailer with
fetchcalls to your provider's API, keeping the API key in a secret.