EmailMail MessagesReusable Email Templates

Reusable Email Templates

Create reusable email templates using MailMessage factory functions

Last updated:

Reusable Email Templates

You can create reusable email templates using factory functions that return configured MailMessage instances. This provides a clean way to organize and reuse email logic.

Basic Template Function

import { MailMessage } from "@visulima/email";

const createWelcomeEmail = (user: { name: string; email: string }) => {
    return new MailMessage()
        .to({ email: user.email, name: user.name })
        .from({ email: "noreply@example.com" })
        .subject(`Welcome, ${user.name}!`)
        .html(`<h1>Welcome ${user.name}!</h1><p>Thanks for joining us.</p>`)
        .text(`Welcome ${user.name}! Thanks for joining us.`);
};

Using Template Functions

import { createMail, MailMessage } from "@visulima/email";
import { resendProvider } from "@visulima/email/providers/resend";

const mail = createMail(resendProvider({ apiKey: "re_xxx" }));

const message = createWelcomeEmail({ name: "John", email: "john@example.com" });
const result = await mail.send(message);

Using Templates in Factory Functions

import { MailMessage } from "@visulima/email";
import { renderHandlebars } from "@visulima/email/template/handlebars";

const createWelcomeEmail = async (user: { name: string; email: string }) => {
    const html = await renderHandlebars(
        `
      <h1>Welcome {{name}}!</h1>
      <p>Thanks for joining us on {{date}}.</p>
      `,
        {
            name: user.name,
            date: new Date().toLocaleDateString(),
        },
    );

    return new MailMessage().to({ email: user.email, name: user.name }).from({ email: "noreply@example.com" }).subject(`Welcome, ${user.name}!`).html(html);
};

Complex Template Example

import { MailMessage } from "@visulima/email";
import { renderHandlebars } from "@visulima/email/template/handlebars";
import { readFile } from "node:fs/promises";

const createOrderConfirmationEmail = async (order: {
    id: string;
    customer: { name: string; email: string };
    items: Array<{ name: string; price: number }>;
    total: number;
}) => {
    const html = await renderHandlebars(await readFile("./templates/order-confirmation.hbs", "utf-8"), { order });

    const message = new MailMessage()
        .to({ email: order.customer.email, name: order.customer.name })
        .from({ email: "orders@example.com", name: "Order Confirmation" })
        .subject(`Order Confirmation #${order.id}`)
        .html(html);

    await message.attachFromPath(`./invoices/${order.id}.pdf`, {
        filename: `invoice-${order.id}.pdf`,
    });

    return message;
};

Using Classes (Optional)

If you prefer a class-based approach, you can extend MailMessage:

import { MailMessage } from "@visulima/email";

class WelcomeEmail extends MailMessage {
    constructor(user: { name: string; email: string }) {
        super();
        this.to({ email: user.email, name: user.name })
            .from({ email: "noreply@example.com" })
            .subject(`Welcome, ${user.name}!`)
            .html(`<h1>Welcome ${user.name}!</h1><p>Thanks for joining us.</p>`)
            .text(`Welcome ${user.name}! Thanks for joining us.`);
    }
}

// Usage
const mail = createMail(resendProvider({ apiKey: "re_xxx" }));
const message = new WelcomeEmail({ name: "John", email: "john@example.com" });
await mail.send(message);

Next Steps

Support

Contribute to our work and keep us going

Community is the heart of open source. The success of our packages wouldn't be possible without the incredible contributions of users, testers, and developers who collaborate with us every day.Want to get involved? Here are some tips on how you can make a meaningful impact on our open source projects.

Ready to help us out?

Be sure to check out the package's contribution guidelines first. They'll walk you through the process on how to properly submit an issue or pull request to our repositories.

Submit a pull request

Found something to improve? Fork the repo, make your changes, and open a PR. We review every contribution and provide feedback to help you get merged.

Good first issues

Simple issues suited for people new to open source development, and often a good place to start working on a package.
View good first issues