You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

better-mail

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

better-mail

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

1.0.1
latest
Source
npmnpm
Version published
Weekly downloads
0
-100%
Maintainers
1
Weekly downloads
 
Created
Source

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

FeatureDescription
🚀 Multiple ProvidersSend emails via SMTP, Resend, or SendGrid
🎨 Template EnginesUse React, MJML, or Handlebars for beautiful emails
🔒 TypeScript FirstFully typed for better developer experience
🛡️ Robust Error HandlingCustom error classes for clear debugging
🔇 Silent by DefaultNo console output unless explicitly enabled
🎯 Security FocusedRegular security audits and vulnerability scanning
📊 Comprehensive Testing80%+ test coverage with unit and integration tests
🏗️ Modern DevelopmentESLint, 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?

  • Server-side only: Email sending requires SMTP connections, API keys, and server resources
  • Security: API keys and credentials should never be exposed to the browser
  • Dependencies: Uses Node.js-specific packages like nodemailer, winston, etc.
  • 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

  • Fork the repository
  • Create a feature branch (git checkout -b feature/amazing-feature)
  • Commit your changes (git commit -m 'Add amazing feature')
  • Push to the branch (git push origin feature/amazing-feature)
  • 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

Keywords

email

FAQs

Package last updated on 17 Jun 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

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.