Send emails with Express.js

In this quickstart, you'll learn how to send transactional emails from your Express.js app with Sidemail. You'll set up the SDK, send your first email, and see examples for common use cases like welcome emails, password resets, and scheduled reports.

Before you start

  1. Create a Sidemail account → get your API key
  2. Add a sending domain → set up your domain for sending

1. Install

npm install sidemail

2. Add your API key

Add your Sidemail API key to .env (make sure you have dotenv installed):

SIDEMAIL_API_KEY=your-api-key

3. Setup

Create a sidemail.js file that exports the configured instance.

// create file -> sidemail.js

const configureSidemail = require("sidemail");

const sidemail = configureSidemail({
	apiKey: process.env.SIDEMAIL_API_KEY,
});

module.exports = sidemail;

4. Send a welcome email

Send an email when a user registers.

// routes/auth.js
const express = require("express");
const router = express.Router();
const sidemail = require("./sidemail");

router.post("/register", async (req, res, next) => {
	try {
		const { email, name } = req.body;

		// ... create user in database ...

		await sidemail.sendEmail({
			toAddress: email,
			fromAddress: "[email protected]",
			fromName: "Your App",
			templateName: "Welcome",
			templateProps: {
				firstName: name,
			},
		});

		res.status(201).json({ message: "User registered" });
	} catch (error) {
		next(error);
	}
});

module.exports = router;

5. Send a password reset email

// routes/auth.js
router.post("/forgot-password", async (req, res, next) => {
	try {
		const { email } = req.body;
		const token = "secure-reset-token"; // Generate this securely

		await sidemail.sendEmail({
			toAddress: email,
			fromAddress: "[email protected]",
			fromName: "Your App",
			templateName: "Password Reset",
			templateProps: {
				actionUrl: `https://myapp.com/reset/${token}`,
			},
		});

		res.json({ message: "Reset email sent" });
	} catch (error) {
		next(error);
	}
});

6. Send a weekly report (Cron Task)

For scheduled tasks in an Express app, you can use a library like node-cron.

// jobs/weekly-report.js
const cron = require("node-cron");
const sidemail = require("./sidemail");

// Run every Monday at 8:00 AM
cron.schedule("0 8 * * 1", async () => {
	const newSignups = 150; // Fetch from DB
	const chartData = [100, 200, 300, 400, 200, 300, 200, 500];

	try {
		await sidemail.sendEmail({
			toAddress: "[email protected]",
			fromAddress: "[email protected]",
			fromName: "My App",
			templateName: "Weekly Report",
			templateProps: {
				signups: newSignups,
				chart: chartData,
			},
		});
		console.log("Weekly report sent");
	} catch (error) {
		console.error("Failed to send weekly report", error);
	}
});

7. Send email via Event Emitter

Decouple email sending from your routes by using Node.js EventEmitter.

// events.js
const EventEmitter = require("events");
const sidemail = require("./sidemail");

class AppEmitter extends EventEmitter {}
const appEmitter = new AppEmitter();

appEmitter.on("userRegistered", async (user) => {
	try {
		await sidemail.sendEmail({
			toAddress: user.email,
			fromAddress: "[email protected]",
			fromName: "My App",
			templateName: "Welcome",
		});
	} catch (error) {
		console.error("Failed to send welcome email", error);
	}
});

module.exports = appEmitter;

Usage in route:

// routes/auth.js
const appEmitter = require("../events");

router.post("/register", async (req, res, next) => {
	// ... create user ...
	const user = { email: "[email protected]", name: "Alex" };

	// Emit the event
	appEmitter.emit("userRegistered", user);

	res.status(201).json({ message: "User registered" });
});

8. Send HTML email

You can use template literals or a template engine like EJS or Pug to generate HTML.

router.post("/send-invoice", async (req, res, next) => {
	try {
		const amount = 99;
		const html = `
      <div>
        <h1>Invoice</h1>
        <p>Amount due: $${amount}</p>
      </div>
    `;

		await sidemail.sendEmail({
			toAddress: "[email protected]",
			fromAddress: "[email protected]",
			fromName: "Your App",
			subject: "Your Invoice",
			html: html,
		});

		res.json({ message: "Invoice sent" });
	} catch (error) {
		next(error);
	}
});

9. Send Markdown email

Store your markdown content in a file and load it (learn more).

const fs = require("fs");
const path = require("path");

router.post("/send-markdown", async (req, res, next) => {
	try {
		const markdown = fs.readFileSync(
			path.join(__dirname, "../templates/emails/welcome.md"),
			"utf8"
		);

		// Subject and sender are defined in the markdown frontmatter
		await sidemail.sendEmail({
			toAddress: "[email protected]",
			markdown: markdown,
			templateProps: {
				name: "John",
				link: "https://example.com",
			},
		});

		res.json({ message: "Email sent" });
	} catch (error) {
		next(error);
	}
});

10. Send plain text email

await sidemail.sendEmail({
	toAddress: "[email protected]",
	fromAddress: "[email protected]",
	fromName: "Your App",
	subject: "Hello",
	text: "Hello! 👋",
});

11. Schedule email

Send email later. Set scheduledAt to an ISO date string.

const scheduledAt = new Date(Date.now() + 60 * 60 * 1000).toISOString();

await sidemail.sendEmail({
	toAddress: "[email protected]",
	fromAddress: "[email protected]",
	fromName: "Your App",
	templateName: "Welcome",
	templateProps: { firstName: "Alex" },
	scheduledAt: scheduledAt,
});

12. Send with attachment

Use the sidemail.fileToAttachment helper to attach files.

const fs = require("fs");
const pdfData = fs.readFileSync("./invoice.pdf");
const attachment = sidemail.fileToAttachment("invoice.pdf", pdfData);

await sidemail.sendEmail({
	toAddress: "[email protected]",
	fromAddress: "[email protected]",
	fromName: "Your App",
	subject: "Your invoice",
	text: "See attached.",
	attachments: [attachment],
});

13. Handle errors

In Express, pass errors to the global error handler using next(error).

try {
	await sidemail.sendEmail({
		/* ... */
	});
} catch (error) {
	next(error);
}