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. 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;

3. 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;

4. 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);
	}
});

5. 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);
	}
});

6. 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);
	}
});

7. 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);
	}
});

8. Send plain text email

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

9. 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,
});

10. 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],
});

11. Handle errors

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

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