npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@hodfords/nestjs-mailer

v10.1.2

Published

Simplifies sending emails in NestJS apps

Downloads

281

Readme

Installation 🤖

Install the nestjs-mailer package with:

npm install @hodfords/nestjs-mailer --save

To configure the mailer module dynamically, use forRoot to define your email template renderers, transport settings, and default sender email.

export const mailConfig = MailerModule.forRoot({
    renders: {
        adapters: [
            new HbsAdapter({
                templateFolder: path.join(env.ROOT_PATH, `mails/templates/${getEmailFolder()}`),
                defaultVariable: async () => getMailConfigurations()
            }),
            new TranslateAdapter((text: string, options: any) => trans(text, options)),
            new MjmlAdapter()
        ],
		transport: env.MAILER_URL,
        defaultFrom: env.CONTACT_MAIL_ADDRESS
    },
    ...
});

For more advanced use cases where additional services or repositories are required, you can register the module using forRootAsync. This allows injecting services, repositories, or even database connections for more complex setups

export const mailConfig = MailerModule.forRootAsync({
    imports: [CoreModule],
    inject: [Connection, StorageService],
    useFactory: (connection: Connection, storageService: StorageService) => {
        const settingRepo = connection.getCustomRepository(SettingRepository);
        const hbsAdapter = new HbsAdapter({
            templateFolder: path.join(env.ROOT_PATH, `mails/templates/${getEmailFolder()}`),
            defaultVariable: async (mail: BaseMail) => {
                const variables = getMailConfigurations();
                if (mail.isWhitelabeled) {
                    const setting = await settingRepo.findOne({ tenant: mail.tenantId });
                    variables.logoUrl = await storageService.generateBlobUrl(setting.blobLogo);
                }
                return variables;
            }
        });
        return {
            renders: {
                adapters: [
                    hbsAdapter,
                    new TranslateAdapter((text: string, options: any) => trans(text, options)),
                    new MjmlAdapter()
                ]
            },
            transport: env.MAILER_URL,
            defaultFrom: env.CONTACT_MAIL_ADDRESS
        };
    }
});

Usage 🚀

Adapters

Currently, nestjs-mailer supports the following adapters:

  • HbsAdapter: For rendering Handlebars templates with dynamic variables and templates.
  • TranslateAdapter: For handling multi-language support and translations.
  • MjmlAdapter: For generating responsive HTML emails using MJML templates.

Defining an Email

To define a custom email, extend the BaseMail class and specify the email subject, template path, and data.

Here's an example of how to define a WelcomeEmail:

import { BaseMail } from '@hodfords/nestjs-mailer';

export class WelcomeMail extends BaseMail {
    constructor(private email: string) {
        super();
    }

    get subject(): string {
        return 'Welcome to Hodfords!';
    }

    get template(): string {
        return path.join(env.ROOT_PATH, 'welcome-mail.mail.hbs');
    }

    data(): Record<string, any> {
        return {
            content:
                "Welcome to our system! We're excited to have you on board and look forward to providing you with a seamless and enjoyable experience."
        };
    }

    get to(): string {
        return this.email;
    }
}

Sending an Email

To send an email, inject the MailerService into your service and utilize the appropriate method for sending emails

import { MailService } from '@hodfords/nestjs-mailer';

@Injectable()
class YourService {
    constructor(private mailService: MailerService) {}
}

You have two options for sending emails:

  • Send Immediately: Send a single email right away.
1. const mail = new WelcomeMail(user.email);
await this.mailService.send(mail);
  • Add to Queue: Use this method when you need to send a large number of emails. Emails will be queued and sent asynchronously.
for (const user of users) {
    const mail = new WelcomeMail(user.email);
    await this.mailService.addToQueue(mail);
}

License 📝

This project is licensed under the MIT License