JSPM

better-mail

1.0.1
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 6
  • Score
    100M100P100Q58896F
  • License MIT

A world-class Node.js email sending library with support for multiple providers and template engines

Package Exports

  • better-mail
  • better-mail/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (better-mail) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

BetterMail

BetterMail Logo

A world-class Node.js email sending library with support for multiple providers and template engines

CI/CD npm version License: MIT TypeScript Coverage

DocumentationExamplesGitHubDiscord

✨ Features

Feature Description
🚀 Multiple Providers Send emails via SMTP, Resend, or SendGrid
🎨 Template Engines Use React, MJML, or Handlebars for beautiful emails
🔒 TypeScript First Fully typed for better developer experience
🛡️ Robust Error Handling Custom error classes for clear debugging
🔇 Silent by Default No console output unless explicitly enabled
🎯 Security Focused Regular security audits and vulnerability scanning
📊 Comprehensive Testing 80%+ test coverage with unit and integration tests
🏗️ Modern Development ESLint, Prettier, Husky, and conventional commits

🚀 Quick Start

Installation

npm install better-mail

Basic Usage

import { createMailer, send } from 'better-mail';

// Initialize with your preferred provider
createMailer({
  provider: 'smtp',
  smtp: {
    host: process.env.SMTP_HOST!,
    port: Number(process.env.SMTP_PORT),
    user: process.env.SMTP_USER!,
    pass: process.env.SMTP_PASS!,
    from: process.env.SMTP_FROM!,
  },
});

// Send an email
await send({
  to: 'recipient@example.com',
  template: 'welcome',
  templateEngine: 'react',
  variables: { name: 'Alice' },
});

📱 React App Compatibility

❌ NO - This library is NOT compatible with React apps running in the browser.

BetterMail is a Node.js server-side library designed for:

  • Backend applications (Express, Fastify, Koa, etc.)
  • Serverless functions (AWS Lambda, Vercel Functions, etc.)
  • CLI tools and scripts
  • API servers and microservices

Why not for React apps?

  1. Server-side only: Email sending requires SMTP connections, API keys, and server resources
  2. Security: API keys and credentials should never be exposed to the browser
  3. Dependencies: Uses Node.js-specific packages like nodemailer, winston, etc.
  4. Architecture: Designed for server-to-server communication, not client-side operations

For React apps, use:

  • Frontend: React components for email templates (✅ Supported)
  • Backend: BetterMail for actual email sending (✅ Recommended)
  • API: Create an endpoint that uses BetterMail to send emails

Example Architecture

// Frontend (React app)
const sendWelcomeEmail = async userData => {
  const response = await fetch('/api/send-welcome-email', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(userData),
  });
  return response.json();
};

// Backend (Node.js API)
import { createMailer, send } from 'better-mail';

createMailer({ provider: 'smtp' /* config */ });

app.post('/api/send-welcome-email', async (req, res) => {
  try {
    await send({
      to: req.body.email,
      template: 'welcome',
      templateEngine: 'react',
      variables: req.body,
    });
    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

📚 Documentation

🔧 Configuration

Environment Variables

Create a .env file in your project root:

# SMTP Configuration
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=your-user
SMTP_PASS=your-pass
SMTP_FROM=from@example.com

# Resend Configuration
RESEND_API_KEY=re_123
RESEND_FROM=from@example.com

# SendGrid Configuration
SENDGRID_API_KEY=SG.123
SENDGRID_FROM=from@example.com

Provider Configuration

import { createMailer } from 'better-mail';

// SMTP
createMailer({
  provider: 'smtp',
  smtp: {
    host: 'smtp.example.com',
    port: 587,
    user: 'user@example.com',
    pass: 'password',
    from: 'from@example.com',
  },
});

// Resend
createMailer({
  provider: 'resend',
  resend: {
    apiKey: 're_123',
    from: 'from@example.com',
  },
});

// SendGrid
createMailer({
  provider: 'sendgrid',
  sendgrid: {
    apiKey: 'SG.123',
    from: 'from@example.com',
  },
});

Logging Configuration

BetterMail is silent by default - no console output unless explicitly enabled:

// Silent (default) - no console output
createMailer({
  provider: 'smtp',
  smtp: {
    /* config */
  },
  logging: {
    silent: true, // or level: 'silent'
  },
});

// Enable logging for debugging
createMailer({
  provider: 'smtp',
  smtp: {
    /* config */
  },
  logging: {
    level: 'debug', // 'error' | 'warn' | 'info' | 'debug'
  },
});

// Disable all logging (including file logs)
createMailer({
  provider: 'smtp',
  smtp: {
    /* config */
  },
  logging: {
    silent: true,
  },
});

📧 Template Engines

React Templates

Create templates/welcome.tsx:

import * as React from 'react';

export const subject = ({ name }: { name: string }) =>
  `Welcome to BetterMail, ${name}!`;

export const text = ({ name }: { name: string }) =>
  `Hi ${name},\n\nWelcome to BetterMail!`;

export function welcome({ name }: { name: string }) {
  return (
    <html>
      <body style={{ fontFamily: 'Arial, sans-serif' }}>
        <h1>Hi {name} 👋</h1>
        <p>Welcome to BetterMail!</p>
      </body>
    </html>
  );
}

export default welcome;

Default Welcome Template

BetterMail includes a beautiful, customizable welcome template:

// Use the built-in welcome template
await send({
  to: 'user@example.com',
  template: 'default-welcome',
  templateEngine: 'react',
  variables: {
    name: 'John Doe',
    company: 'MyApp',
    features: ['Feature 1', 'Feature 2', 'Feature 3'],
    primaryColor: '#3B82F6', // Customize colors
    secondaryColor: '#1F2937',
    accentColor: '#10B981',
  },
});

MJML Templates

Create templates/newsletter.mjml:

<mjml>
  <mj-body>
    <mj-section>
      <mj-column>
        <mj-text font-size="20px">Hi {{name}} 👋</mj-text>
        <mj-text>Check out our latest newsletter!</mj-text>
      </mj-column>
    </mj-section>
  </mj-body>
</mjml>

Handlebars Templates

Create templates/invoice.hbs:

<html>
  <body style="font-family: Arial, sans-serif;">
    <h1>Invoice for {{customerName}}</h1>
    <p>Amount: {{amount}}</p>
    <p>Due Date: {{dueDate}}</p>
  </body>
</html>

🛠️ Development

Prerequisites

  • Node.js 16+
  • npm or yarn

Setup

# Clone the repository
git clone https://github.com/better-mail/better-mail.git
cd better-mail

# Install dependencies
npm install

# Set up Git hooks
npm run prepare

# Build the project
npm run build

# Run tests
npm test

Available Scripts

npm run build          # Build the project
npm run test           # Run tests
npm run test:watch     # Run tests in watch mode
npm run test:coverage  # Run tests with coverage
npm run lint           # Run ESLint
npm run lint:fix       # Fix ESLint issues
npm run format         # Format code with Prettier
npm run docs           # Generate documentation
npm run example:welcome # Run welcome template example

🤝 Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

Development Workflow

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🆘 Support

🙏 Acknowledgments


Made with ❤️ by the BetterMail Team

GitHub stars GitHub forks