🚨 Shai-Hulud Strikes Again:834 Packages Compromised.Technical Analysis
Socket
Book a DemoInstallSign in
Socket

@openagenda/mails

Package Overview
Dependencies
Maintainers
2
Versions
32
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@openagenda/mails

Build and send responsive e-mails from Node.js.

latest
Source
npmnpm
Version
5.0.0
Version published
Maintainers
2
Created
Source

@openagenda/mails

Build and send responsive e-mails from Node.js.

MJML + EJS + Nodemailer = :heart:

Getting Started

This project allows you to send mails from templates.

Installing

yarn add @openagenda/mails

# or `npm i @openagenda/mails`

Initializing

Before using it you must initialize the service, the configuration needs to know where to find the templates, how to send them and optionally the default values for each send (for example: domain, lang).

const createMails = require('@openagenda/mails');

/* Default configuration */

const config = {
  // Templating
  templatesDir:
    process.env.MAILS_TEMPLATES_DIR || path.join(process.cwd(), 'templates'),
  mjmlConfigPath: process.cwd(),

  // Mailing
  transport: {
    pool: true,
    host: '127.0.0.1',
    port: '1025', // Mailcatcher port
    maxMessages: Infinity,
    maxConnections: 20,
    rateLimit: 14, // 14 emails/second max
    rateDelta: 1000,
  },
  defaults: {},

  // Queuing
  disableVerify: false,
};

const mails = await createMails(config).catch((error) => {
  console.log('Error on initializing service mails', error);
  throw error;
});

console.log('Service mails initialized');

More details on the options in the API section.

Example

const { results, errors } = await mails.send({
  template: 'helloWorld',
  to: {
    address: 'user@example.com',
    data: { username: 'bertho' },
    lang: 'fr',
  },
});

Building templates

See @openagenda/mails-editor

Structure

Each template has a folder with its name, in there must be at least one file index.mjml and fixtures.js (or a fixtures folder with some js files).

index.mjml is the entry point of your template, it can be split into different partials (see include of EJS).
text.ejs is the text version of your template.
subject.ejs is the subject of the mail corresponding to your template.
fixtures.js exports data that are used in the template to preview as in production. locales folder with %lang%.json files, where %lang% is the language code (en.json, fr.json, etc).

The structure of your templates folder can look like this:

/templates
  /helloWorld
    fixtures.js
    index.mjml
    text.ejs
    subject.ejs
  /accountActivation
    /locales
      en.json
      fr.json
    /fixtures
      fixture1.js
      fixture2.js
    index.mjml
    text.ejs
    subject.ejs

API

Configuration

createMails(options)

Usage

const createMails = require('@openagenda/mails');

/* Dafault values */

const mails = await createMails({
  // Templating
  templatesDir:
    process.env.MAILS_TEMPLATES_DIR || path.join(process.cwd(), 'templates'),
  mjmlConfigPath: process.cwd(),

  // Mailing
  transport: {
    pool: true,
    host: '127.0.0.1',
    port: '1025',
    maxMessages: Infinity,
    maxConnections: 20,
    rateLimit: 14, // 14 emails/second max
    rateDelta: 1000,
  },
  defaults: {},

  // Queuing
  queue: BullMQ.Queue,
  createWorker: (jobProcessor) => BullMQ.Worker,
});

Arguments

NameTypeDescription
optionsObjectThe options to initializing the service.

options

ValueRequiredDescription
templatesDir*The folder path containing your templates.
mjmlConfigPathUses the .mjmlconfig file in the specified path or directory to include custom components.
transport*An object that defines connection data, it's the first argument of nodemailer.createTransport (SMTP or other).
defaultsAn object that is going to be merged into every message object. This allows you to specify shared options, for example to set the same from address for every message. It's the second argument of nodemailer.createTransport.
queue*A BullMQ queue.
createWorker*A function that take a jobProcessor as argument and return a BullMQ worker.
disableVerifyA Boolean that allows to disable the verification of the transporter connection, it is done in the init.
loggerAn object for the method setModuleConfig of @openagenda/logs

During initialization a transporter is added to the config, you can use it raw from anywhere with a require of @openagenda/mails/config.

Mailing

send(options)

This is the main method, this function returns a Promise with one of these values:

  • an array of BullMQ jobs if the queue is activated
  • an array of nodemailer sendMail results if the queue is disabled

This is a nodemailer sendMail overload with some notable differences:

  • You can use a template.
  • The email addresses are validated before sending.
  • The sending of emails is never grouped, the recipients of the messages are always separated, which makes it possible to attach data by recipient.
  • Emails can be stored in an external queue while waiting for their turn.

Usage

await mails({
  template: 'helloWorld',
  to: {
    address: 'user@example.com',
    data: { username: 'bertho' },
    lang: 'fr',
  },
  queue: false,
});

Arguments

NameTypeDescription
optionsObjectThe options to sending email(s).

Options

ValueRequiredDescription
templateA string that is the name of the template, is equal to the folder name.
dataAn object that contains the data to passed to the template, this can be overloaded for each recipient.
langA string that defines the default language that will be applied to all recipients without lang.
to*A recipient or array of recipients.
queueA Boolean, if false do not queue job and execute directly.
...All other nodemailer options are normally handled by nodemailer, see the other options here.

Error handling
sendMail does not throw an error in case of problem, it returns an object { results, errors }.
It allows not to block the sending of emails for all when there is only a malformed email address in the batch, for example.

Recipients
You will find more information on the nodemailer documention (https://nodemailer.com/message/addresses/).
The main difference is that the email is sent separately to each recipient, one mail/one recipient.
If you want to add specific data to a recipient for the template (for example: its name, age, role, etc.) you must use an object with the data key, the language of the recipient can be in the lang key:

{
  address: 'user@example.com',
  data: { username: 'bertho' },
  lang: 'fr'
}

Defaults
It's an object that is going to be merged into every message object. This allows you to specify shared options, for example to set a default from address for every message.

Data order
The data come from several sources, they are Object.assigned in this order:

  • data from the send options
  • data from the current recipient (recipient.data)
  • data from defaults.data lastly for conserve values like domain, etc

Language
As for data, the language can be overloaded in several places, in this order:

  • { lang } from defaults.
  • lang from the send options
  • lang from the current recipient (recipient.lang)

The __ and lang values are passed to the template.

task()

If you can send a lot of messages it is better to use the BullMQ queue rather than the memory.

To use a rateLimit you will need to boot a transport with the pool: true option.
Learn more at Delivering bulk mail and Pooled SMTP

Make sure to run the task before sending any email, just after the initialization looks correct.

task returns a promise that should not be waited.

Usage

mails.task();

ProTip: You can disable the queue for all email sends by setting { defaults: { queue: false } } to initialization.

Templating

The render and compile methods allow you to use your MJML templates, coupled with EJS for replacing variables and loops, among others.

These methods add __ method in the data for use the translations in the templates (json files in locales directory).

The opts argument corresponds to the EJS argument described here.

render(templateName [, data = {}, opts = {}])

Returns a Promise that resolves an Object containing three strings:

  • html
  • text
  • subject.

Arguments

NameTypeDescription
templateNamestringThe name of the template, is equal to the folder name.
dataobjectAn object that contains the data to passed to the template.
optionsObjectThe opts argument corresponds to the EJS argument described here.

With the ability to add disableHtml, disableText and disableSubject, all three booleans.

Options

ValueRequiredDescription
disableHtmlA Boolean, if true then html is not rendered and is equal null.
disableTextA Boolean, if true then text is not rendered and is equal null.
disableSubjectA Boolean, if true then subject is not rendered and is equal null.
...All other EJS options are normally handled by EJS, see the other options here.

compile(templateName [, opts = {}])

Returns a Promise that resolves an Object containing three functions:

  • html(data)
  • text(data)
  • subject(data).

Arguments

NameTypeDescription
templateNamestringThe name of the template, is equal to the folder name.
optionsObjectThe opts argument corresponds to the EJS argument described here.

With the ability to add disableHtml, disableText and disableSubject, all three booleans.

Options

ValueRequiredDescription
disableHtmlA Boolean, if true then html is not compiled and is equal null.
disableTextA Boolean, if true then text is not compiled and is equal null.
disableSubjectA Boolean, if true then subject is not compiled and is equal null.
...All other EJS options are normally handled by EJS, see the other options here.

Testing

Running the tests

For a single run of all suites of tests:

yarn test

You can add the --watch option to watch the tests related to the files you modify, or --watchAll to run all tests with each change.

--coverage option is available to indicates that test coverage information should be collected and reported in the output.

These options are the most common, but you can use other Jest CLI options.

Adding tests

If you want to create your own tests, you can refer to the Testing SMTP section on the nodemailer documentation.

FAQs

Package last updated on 22 Aug 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts