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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@brojs/mailer

v2.0.6

Published

mailer helper

Readme

@brojs/mailer

Пакет для работы с email в проектах BroJS: очередь писем с таймером, шаблоны с подстановкой {{key}}, резервный SMTP.

Установка

npm install @brojs/mailer

Использование

Инициализация

Один раз при старте приложения вызвать init():

const path = require('path');
const { init, configs } = require('@brojs/mailer');

init({
    userName: process.env.SMTP_MAIL_LOGIN,
    password: process.env.SMTP_MAIL_PASSWORD,
    smtpConfig: configs.yandex,
    adminMails: process.env.ADMIN_MAILS,
    templatesDir: path.join(process.cwd(), 'email', 'templates'),
});

Опция templatesDir (необязательная) — путь к папке с HTML-шаблонами. При инициализации все файлы с расширением .html (регистронезависимо) загружаются и регистрируются по имени без расширения (например, notification.html → шаблон notification). Обрабатываются только файлы непосредственно в указанной папке, без рекурсии. Если путь не передан, пустой, не существует или не является директорией, загрузка не выполняется (при несуществующей/не-директории выводится предупреждение в консоль). Дубликаты имён: последний файл перезаписывает предыдущий.

Отправка писем

const { Request, addToQueue } = require('@brojs/mailer');

addToQueue(new Request({
    email: '[email protected]',
    header: 'Тема письма',
    body: '<p>Текст письма</p>',
}));

Шаблоны

Регистрация вручную: addTemplate(name, template). Подстановки в шаблоне: {{key}}.

Отправка по шаблону:

const { Request, addTemplateQueue } = require('@brojs/mailer');

addTemplateQueue(
    'welcome',
    new Request({ email: '[email protected]', header: 'Добро пожаловать', body: '' }),
    { name: 'Иван', link: 'https://example.com/activate' }
);

Если задан templatesDir, шаблоны из папки доступны сразу после init() — отдельный обход через fs в приложении не нужен.

Опции init()

| Опция | Обязательная | Описание | |-------|--------------|----------| | userName | да | Логин SMTP (адрес отправителя) | | password | да | Пароль SMTP | | adminMails | да | Адреса администраторов | | smtpConfig | да | Объект { host, port, secure }, можно configs.yandex | | reserveLogin, reservePasswd, reserveSmtpConfig | нет | Резервный SMTP при сбое основной отправки | | queueTimer | нет | Интервал опроса очереди, мс (по умолчанию 1000) | | batchSize | нет | Сколько писем за один цикл (по умолчанию 1) | | batchInterval | нет | Пауза между письмами в батче, мс (по умолчанию 0) | | templatesDir | нет | Путь к папке с .html шаблонами; загрузка при инициализации |

Загрузка шаблонов из папки (templatesDir)

  • Файлы: только с расширением .html или .HTML (регистронезависимо).
  • Имя шаблона: имя файла без расширения (notification.htmlnotification). Файл только с расширением (например .html) пропускается.
  • Кодировка: UTF-8.
  • Уровень: только файлы в указанной папке, без подпапок.
  • Ошибки: несуществующая или не-директория — предупреждение в консоль, приложение не падает. Ошибка чтения отдельного файла — сообщение в консоль, обработка остальных продолжается.

Разработка

npm test

Лицензия

MIT