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

ts-mailkit

v3.2.0

Published

Strictly typed, modular, and composable email composition and dispatch library for TypeScript and modern edge runtimes.

Readme

ts-mailkit

Strictly typed, modular, and composable email composition and dispatch library for TypeScript and modern edge runtimes.

Works seamlessly in Node.js, Cloudflare Workers (workerd), Bun, Deno, Next.js, and Vercel Edge Functions.


Key Features

  • Type-Safe DTOs: Strongly-typed Data Transfer Objects for transactional emails (verification, password reset, 2FA, magic links, newsletters).
  • Pluggable Transports (IEmailSender): Decoupled transport adapter interface with built-in senders:
    • CpaasHttpSender (Zoho CPaaS transactional API via native fetch; rejects requests over 500 recipients before dispatch unless loopBatch is enabled).
    • MemoryEmailSender (In-memory mock transport for unit and integration testing).
    • ConsoleEmailSender (Formatted terminal logger for local development).
  • Zero Runtime Dependencies: Core uses standard web APIs (global fetch), ensuring zero heavy dependencies and complete edge compatibility.
  • Separation of Concerns: Strict decoupling between:
    1. DTO schema and validation.
    2. Template building and responsive HTML rendering.
    3. Dispatch via the chosen transport adapter.
  • Multitenant & Dynamic Branding: Configure global branding, top-center logos, or pass a dynamic brand name resolver for multi-tenant applications.
  • Top-Center Brand Logo: Display your brand or company logo top-center with automatic HTTP(S) URL validation.
  • Auto Plain-Text Fallbacks: When sending custom or raw HTML, accessible plain-text equivalents are cleanly generated automatically if not explicitly provided.
  • RFC 5322 Address Parser: Optional utility to safely parse "Display Name <[email protected]>" strings into structured address objects.
  • Template Preview: Inspect demo-newsletter.html directly in the root folder to view the responsive default email template before installing.
  • Dual ESM & CommonJS: Full support for import and require with first-class TypeScript declaration maps.

Installation

Install using your preferred package manager:

# pnpm
pnpm add ts-mailkit

# npm
npm install ts-mailkit

# yarn
yarn add ts-mailkit

# bun
bun add ts-mailkit

Quick Start

1. Initialize Transport & Client

import { createMailKit, CpaasHttpSender, EmailTemplateFactory } from "ts-mailkit";

// Configure the Zoho CPaaS HTTP transport
const transport = new CpaasHttpSender({
  apiToken: process.env.CPAAS_API_KEY!,
  apiHost: "cpaas.zoho.com", // or 'cpaas.zoho.eu', 'cpaas.zoho.in'
  from: { address: "[email protected]", name: "Acme App" },
});

// Initialize the MailKit client
const mailer = createMailKit({
  transport,
  defaultBrandName: "Acme App",
});

2. Compose and Send Using Typed DTOs

// 1. Create a strongly typed email verification DTO
const verificationEmail = EmailTemplateFactory.createEmailVerification({
  username: "Alex",
  verificationUrl: "https://app.example.com/verify?token=xyz123",
  otp: "482910",
});

// 2. Dispatch via MailKit
await mailer.sendMail({
  to: "[email protected]",
  template: verificationEmail,
});

Common Use Cases

1. Built-in Transactional Templates

EmailTemplateFactory provides type-safe constructors for standard transactional patterns:

import { EmailTemplateFactory } from "ts-mailkit";

// Email Verification with OTP
const verifyDto = EmailTemplateFactory.createEmailVerification({
  username: "Jordan",
  verificationUrl: "https://app.com/verify?token=abc",
  otp: "123456",
});

// Password Reset
const resetDto = EmailTemplateFactory.createPasswordReset({
  username: "Jordan",
  resetUrl: "https://app.com/reset?token=abc",
  otp: "654321",
});

// Two-Factor Authentication (2FA)
const twoFactorDto = EmailTemplateFactory.create2FAEmail({
  username: "Jordan",
  otp: "987654",
  magicLink: "https://app.com/2fa/magic?token=abc",
});

// Magic Link Sign-in
const magicLinkDto = EmailTemplateFactory.createMagicLinkEmail({
  username: "Jordan",
  magicLink: "https://app.com/auth/magic?token=abc",
});

// Newsletter / Announcement
const newsDto = EmailTemplateFactory.createNewsLetter({
  subject: "Product Update - Fall 2026",
  header: "Introducing New Features",
  body: "Here is what our team shipped this month.",
  imageUrl: "https://cdn.example.com/hero.png",
  actionUrl: "https://app.com/blog/update",
  actionText: "Read Release Notes",
});

2. Custom Branding & Multi-tenancy

You can instantiate EmailTemplateFactory with brand-level defaults:

const tenantFactory = new EmailTemplateFactory({
  brandName: "St. Patrick High School",
  logoUrl: "https://school.edu/assets/logo.png",
  securityMessage:
    "If you did not make this request, contact our school IT administration immediately.",
  footer: (brand) => `© ${new Date().getFullYear()} ${brand}. Authorized educational portal.`,
});

const studentEmail = tenantFactory.createEmailVerification({
  username: "Student",
  verificationUrl: "https://school.edu/verify",
  otp: "554433",
});

Or pass a dynamic tenant resolver to MailKit:

const mailer = createMailKit({
  transport,
  defaultFrom: "[email protected]",
  brandNameResolver: async () => {
    // Dynamically retrieve active tenant brand from request context or DB
    return "Springfield Academy";
  },
});

3. Testing with MemoryEmailSender

Easily write unit and integration tests without hitting third-party APIs or mocking network sockets:

import { describe, it, expect, beforeEach } from "vitest";
import { createMailKit, MemoryEmailSender, EmailTemplateFactory } from "ts-mailkit";

describe("User Registration Email", () => {
  let memoryTransport: MemoryEmailSender;
  let mailer: ReturnType<typeof createMailKit>;

  beforeEach(() => {
    memoryTransport = new MemoryEmailSender();
    mailer = createMailKit({ transport: memoryTransport });
  });

  it("sends verification code to the registered user", async () => {
    const dto = EmailTemplateFactory.createEmailVerification({
      username: "Sam",
      verificationUrl: "https://app.com/verify?token=123",
      otp: "889900",
    });

    await mailer.sendMail({ to: "[email protected]", template: dto });

    expect(memoryTransport.count()).toBe(1);
    const sent = memoryTransport.getLastMail();
    expect(sent?.subject).toBe("Verify Your Email Address");
    expect(sent?.html).toContain("889900");
    expect(sent?.text).toContain("Your verification code is: 889900");
  });
});

4. Sending Raw Emails (No Template DTO)

For custom HTML or plain-text messages. When text is omitted, an accessible plain-text fallback is automatically extracted from the html:

await mailer.sendRaw({
  to: [{ address: "[email protected]", name: "Support Team" }],
  subject: "Urgent System Alert",
  html: "<h1>System Alert</h1><p>Database failover completed successfully.</p>",
  // text is optional — auto-converted from html if omitted
  attachments: [
    {
      filename: "report.txt",
      content: "Database log summary...",
      mimeType: "text/plain",
    },
  ],
});

5. Parsing RFC 5322 Email Addresses

If your application receives combined address strings like "Jane Doe <[email protected]>", use the standalone, tree-shakeable parseEmailAddress helper:

import { parseEmailAddress } from "ts-mailkit";

const recipient = parseEmailAddress("Jane Doe <[email protected]>");
// => { address: '[email protected]', name: 'Jane Doe' }

const simple = parseEmailAddress("[email protected]");
// => { address: '[email protected]' }

6. Pluggable Transports (IEmailSender)

You can implement custom transports (e.g. SMTP, Resend, SendGrid, Postmark) by satisfying the IEmailSender interface. Bulk and provider-template capabilities are optional: implement sendBulk, sendKnownTemplate, and/or sendBulkKnownTemplate to enable them. MailKit throws a ConfigurationError if a method is called on a transport that does not implement it.

import type { IEmailSender, SendMailOptions, SendResult } from "ts-mailkit";

export class CustomSmtpSender implements IEmailSender {
  readonly name = "smtp";

  async send(options: SendMailOptions): Promise<SendResult> {
    // Custom dispatch logic using your preferred protocol or client
    return {
      success: true,
      messageId: "custom-id-123",
    };
  }
}

7. Bulk Messaging & Provider-Side Templates

MailKit exposes four canonical send methods. Bulk methods hit the provider's batch endpoints directly and deliver an individual copy to each recipient. Set loopBatch: true on a bulk call to split batches larger than the provider's per-request limit into sequential requests.

// 1. Bulk manual template: the SAME rendered DTO is delivered individually
//    to every recipient (one batch call). For per-recipient content, use
//    sendBulkKnownTemplate below.
await mailer.sendBulkMail({
  to: ["[email protected]", "[email protected]"],
  template: newsletterDto,
  trackClicks: true,
  trackOpens: true,
});

// 2. Single provider-side template (uploaded to Zoho CPaaS / SendGrid beforehand).
await mailer.sendKnownTemplate({
  templateId: "welcome-email",
  to: "[email protected]",
  mergeInfo: { user_name: "Alex" },
});

// 3. Bulk provider-side template with per-recipient merge data.
await mailer.sendBulkKnownTemplate({
  templateId: "welcome-email",
  to: [
    { address: "[email protected]", name: "Alex", mergeInfo: { user_name: "Alex" } },
    { address: "[email protected]", name: "Sam", mergeInfo: { user_name: "Sam" } },
  ],
});

// 4. Oversized batches: split into sequential provider requests instead of
//    throwing when the 500-recipient limit is exceeded.
await mailer.sendBulkMail({
  to: recipients, // e.g. 1,200 addresses
  template: newsletterDto,
  loopBatch: true,
});

Set CpaasHttpConfig.preferTemplateAlias: true to send template_alias instead of template_key. Every transport returns a unified SendResult whose rawResponse field holds the provider's raw response (typed via the exported CpaasSuccessResponse / CpaasErrorResponse types).

Recipient limit: Zoho CPaaS accepts at most 500 recipients per request, counted across to, cc, and bcc. By default, CpaasHttpSender validates this before making any network request and throws a TransportError when exceeded. Pass loopBatch: true to split the to list into sequential requests instead; cc and bcc are included in the first request only so each recipient receives exactly one copy. When a batch is split, SendResult.rawResponse is an array of the provider's responses in request order; a single request keeps the usual object shape.

8. Building Upload-Ready Templates

buildHTMLTemplate and buildPlainTextTemplate turn the canonical EmailTemplateDto into content you can upload to a messaging platform:

import { buildHTMLTemplate, buildPlainTextTemplate, EmailTemplateFactory } from "ts-mailkit";

const dto = EmailTemplateFactory.createSimpleMessage({
  subject: "Welcome",
  header: "Hello",
  body: "Thanks for joining.",
});

const html = buildHTMLTemplate(dto, { primaryColor: "#0f766e", maxWidth: "640px" });
const text = buildPlainTextTemplate(dto);
// Upload `html` / `text` as a provider-side template, then send with `sendKnownTemplate`.

Template Preview

You can inspect what the default responsive email template looks like without writing code or installing the library:

  • 📄 demo-newsletter.html — Standalone, fully pre-rendered HTML newsletter showcasing top-center brand logo, hero banner, typography, call-to-action button, and footer. Generated automatically during the test suite.

Development & Testing

# Install dependencies
pnpm install

# Run unit tests
pnpm test:unit

# Type check
pnpm run typecheck

# Build dual ESM/CJS bundles + .d.ts types
pnpm run build

# Prepublish verification
pnpm run prepublishOnly

License

MIT