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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@masummillat/mailer

v1.0.0

Published

Simple mailer with multiple provider support

Readme

Multi-Provider Mailer Service

A simple, scalable mail service. Supports multiple mail providers, HTML templates, and failover capabilities with direct configuration.

Features

  • 🚀 Simple Factory Pattern: Single factory function handles all use cases
  • 📧 Multiple Provider Support: Nodemailer (SMTP), SendGrid with priority-based failover
  • 🎨 Template System: Handlebars-based HTML templates with file system loading
  • 💪 Automatic Failover: Switches between providers when one fails
  • 🔧 Direct Configuration: Pass configuration directly, no environment variables required
  • 🧪 Testing Ready: Simple initialization for tests and development

Quick Start

Installation

npm install @masummillat/mailer
# or
yarn add @masummillat/mailer

Basic Usage

import { createEmailService } from "@masummillat/mailer";

// Initialize with direct configuration
const emailService = await createEmailService({
  serviceName: "your-service",
  nodemailer: {
    enabled: true,
    priority: 1,
    host: "smtp.gmail.com",
    port: 587,
    secure: false,
    user: "[email protected]",
    password: "your-app-password",
    from: "Your Service <[email protected]>",
  },
});

// Send simple email
const result = await emailService.sendEmail({
  to: "[email protected]",
  subject: "Welcome!",
  html: "<h1>Hello World</h1>",
  text: "Hello World",
});

console.log("Email sent:", result.success);

Configuration

Direct Configuration (Recommended)

const emailService = await createEmailService({
  serviceName: "your-service",
  nodemailer: {
    enabled: true,
    priority: 1,
    host: "smtp.gmail.com",
    port: 587,
    secure: false,
    user: "[email protected]",
    password: "your-app-password",
    from: "Your App <[email protected]>",
  },
  sendgrid: {
    enabled: true,
    priority: 2,
    apiKey: "sg.your-api-key",
    from: "Your App <[email protected]>",
  },
  templates: {
    directory: "./templates",
  },
});

Environment Variables (Alternative)

# Service Configuration
SERVICE_NAME=your-service
NODE_ENV=production

# Nodemailer Provider
YOUR_SERVICE_SMTP_HOST=smtp.gmail.com
YOUR_SERVICE_SMTP_PORT=587
YOUR_SERVICE_SMTP_SECURE=false
[email protected]
YOUR_SERVICE_SMTP_PASS=your-app-password
YOUR_SERVICE_SMTP_FROM="Your App <[email protected]>"

# SendGrid Provider (optional)
YOUR_SERVICE_SENDGRID_ENABLED=true
YOUR_SERVICE_SENDGRID_API_KEY=your-sendgrid-api-key
YOUR_SERVICE_SENDGRID_FROM="Your App <[email protected]>"

Templates

Creating Templates

Create HTML templates in your service:

your-service/
├── templates/
│   ├── welcome.html
│   ├── password-reset.html
│   └── notification.html

Example Template: templates/welcome.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Welcome</title>
  </head>
  <body
    style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;"
  >
    <h1 style="color: #333;">Welcome to {{appName}}!</h1>
    <p>Dear {{userName}},</p>
    <p>Your account has been created successfully.</p>

    <div style="background: #f5f5f5; padding: 20px; margin: 20px 0;">
      <h3>Account Details:</h3>
      <p><strong>Email:</strong> {{userEmail}}</p>
      <p><strong>Registered:</strong> {{registrationDate}}</p>
    </div>

    <p>Best regards,<br />{{appName}} Team</p>
  </body>
</html>

Using Templates

// Send template email
const result = await emailService.sendTemplateEmail(
  "welcome",
  {
    userName: "John Doe",
    appName: "Your Application",
    userEmail: "[email protected]",
    registrationDate: new Date().toLocaleDateString(),
  },
  {
    to: "[email protected]",
  }
);

Advanced Usage

Provider Priority & Failover

const emailService = await createEmailService({
  serviceName: "your-service",
  nodemailer: {
    enabled: true,
    priority: 1, // Primary provider
  },
  sendgrid: {
    enabled: true,
    priority: 2, // Fallback provider
  },
});

Health Monitoring

// Check available providers
const providers = emailService.getProviders();
console.log("Active providers:", providers);

// Health check endpoint
app.get("/health", async (req, res) => {
  const providers = emailService.getProviders();
  res.json({
    status: "healthy",
    mail: {
      healthy: providers.length > 0,
      providers: providers,
    },
  });
});

Framework Integration

Express.js

import express from "express";
import { createEmailService } from "@masummillat/mailer";

const app = express();
let emailService;

app.listen(3000, async () => {
  emailService = await createEmailService({
    serviceName: "your-service",
    // Configuration here
  });
  console.log("Server started with mail service");
});

NestJS

import { Injectable } from "@nestjs/common";
import { createEmailService, SimpleEmailService } from "@masummillat/mailer";

@Injectable()
export class EmailService {
  private emailService: SimpleEmailService;

  async onModuleInit() {
    this.emailService = await createEmailService({
      serviceName: "your-service",
      // Configuration here
    });
  }

  async sendWelcomeEmail(user: any) {
    return this.emailService.sendTemplateEmail("welcome", user, {
      to: user.email,
    });
  }
}

Testing

import { createEmailService } from "@masummillat/mailer";

describe("Email Service", () => {
  it("should send test email", async () => {
    const service = await createEmailService({
      serviceName: "test-service",
      nodemailer: {
        enabled: true,
        priority: 1,
        host: "smtp.ethereal.email", // Test SMTP
        port: 587,
        user: "test-user",
        password: "test-password",
        from: "[email protected]",
      },
    });

    const result = await service.sendEmail({
      to: "[email protected]",
      subject: "Test",
      html: "<p>Test</p>",
    });

    expect(result).toHaveProperty("success");
  });
});

Troubleshooting

Common Issues

  1. "No healthy providers available"

    • Check environment variables with correct SERVICE_NAME prefix
    • Verify SMTP credentials and network connectivity
  2. Template not found

    • Ensure template files exist in templates/ directory
    • Check template naming matches the ID used in code
  3. SMTP Authentication Failed

    • Use App Passwords for Gmail (not regular password)
    • Enable 2-Factor Authentication
  4. SendGrid API Key Invalid

    • Generate new API key with "Mail Send" permissions
    • Verify sender email is verified in SendGrid

Debug Logging

LOG_LEVEL=debug

License

MIT License