包详细信息

emailjs

eleith185.8kMIT5.0.0

send text/html emails and attachments (files, streams and strings) from node.js to any smtp server

自述文件

emailjs 📧✨

Send emails with ease!

This library lets you send rich HTML emails, attachments (from files, streams, or strings), and plain text messages to any SMTP server.

checks

What's to expect from emailjs? 🚀

  • SSL and TLS Support: Secure connections to your SMTP servers.
  • Authentication Galore: Supports popular SMTP authentication methods like PLAIN, LOGIN, CRAM-MD5, and XOAUTH2.
  • Asynchronous Sending: Emails are queued and sent in the background.
  • Rich Content: Send HTML emails and include multiple attachments.
  • Flexible Attachments: Attachments can be files, data streams, or plain strings.
  • UTF-8 Ready: Full support for UTF-8 in headers and body.
  • Built-in Type Declarations: first-class TypeScript support.
  • Greylisting Awareness: Automatically handles greylisting to improve deliverability.

Get Started! 🛠️

Installing

It's super simple!

npm install emailjs

Requirements

  • Access to an SMTP Server.
  • If your email service (like Gmail) uses two-step verification, you'll need an application-specific password.

Quick Examples 🧑‍💻

Here's how easy it is to send emails:

Text-Only Emails

import { SMTPClient } from 'emailjs';

const client = new SMTPClient({
    user: 'your-username',
    password: 'your-password',
    host: 'smtp.your-email.com',
    ssl: true, // Use SSL for secure connection
});

async function sendMyEmail() {
    try {
        const message = await client.sendAsync({
            text: 'Hello from emailjs! This is a test message.',
            from: 'You <your-email@example.com>',
            to: 'Someone <someone@example.com>',
            subject: 'Exciting News from emailjs! 🎉',
        });
        console.log('Email sent successfully:', message);
    } catch (err) {
        console.error('Failed to send email:', err);
    } finally {
        client.smtp.close(); // Don't forget to close the connection!
    }
}

sendMyEmail();

HTML Emails & Attachments

import { SMTPClient, Message } from 'emailjs';

const client = new SMTPClient({
    user: 'your-username',
    password: 'your-password',
    host: 'smtp.your-email.com',
    tls: true,
});

async function sendRichEmail() {
    const htmlContent = `
        <h1>Greetings!</h1>
        <p>This is an <b>HTML email</b> with a lovely picture and an attachment.</p>
        <img src="cid:my-image" alt="Embedded Image" width="150" height="100">
        <p>Check out the attached file!</p>
    `;

    const message = new Message({
        from: 'You <your-email@example.com>',
        to: 'Someone <someone@example.com>',
        subject: 'Your Awesome HTML Email! 🖼️📄',
        attachment: [
            {
                data: htmlContent,
                alternative: true, // This part is the HTML body
                contentType: 'text/html',
            },
            {
                path: 'path/to/your/document.pdf', // Attach a file from disk
                type: 'application/pdf',
                name: 'document.pdf',
            },
            {
                path: 'path/to/your/image.jpg', // Embed an image for the HTML
                type: 'image/jpeg',
                name: 'cool_image.jpg',
                // Reference in HTML with cid:my-image
                headers: { 'Content-ID': '<my-image>' },
            },
        ],
    });

    try {
        await client.sendAsync(message);
        console.log('Rich email sent successfully!');
    } catch (err) {
        console.error('Failed to send rich email:', err);
    } finally {
        client.smtp.close();
    }
}

sendRichEmail();

API Reference 📖

The emailjs library is fully typed, here is a brief overview of most likely to be used methods

new SMTPClient(options)

Create a new client instance to connect to your SMTP server.

const options = {
    user: 'your-username', // 🔑 Username for logging into SMTP
    password: 'your-password', // 🤫 Password for logging into SMTP
    host: 'smtp.your-email.com', // 🌐 SMTP server host (defaults to 'localhost')
    port: 587, // 🔌 SMTP port (defaults: 25 unencrypted, 465 SSL, 587 TLS)
    ssl: true, // 🔒 Boolean or object for immediate SSL connection
    tls: true, // 🔐 Boolean or object (see typescript types) to initiate STARTTLS
    timeout: 5000, // ⏳ Max milliseconds to wait for SMTP responses
    domain: 'your-domain.com', // 🏠 Domain to greet SMTP with (defaults to os.hostname)
    authentication: ['PLAIN', 'LOGIN'], // 🤝 Preferred authentication methods
    logger: console, // 📝 Override the built-in logger (e.g., custom logging)
};

SMTPClient#send(message, callback)

Sends an email message. You can pass a Message instance or a headers object.

client.send(messageObject, (err, details) => {
    if (err) console.error(err);
    else console.log('Message sent:', details);
});

SMTPClient#sendAsync(message)

a promise-based way to send emails! ✨

try {
    const details = await client.sendAsync(messageObject);
    console.log('Message sent:', details);
} catch (err) {
    console.error('Failed to send:', err);
}

new Message(headers)

Constructs an RFC2822-compliant message object.

const headers = {
    from: 'sender@example.com', // 💌 Sender (required!)
    to: 'recipient@example.com', // 📬 Recipients (at least one of to, cc, or bcc)
    cc: 'carbon-copy@example.com', // 👥 CC recipients
    bcc: 'blind-copy@example.com', // 🕵️‍♀️ BCC recipients
    subject: 'Your Subject Here', // 📝 Email subject
    text: 'Plain text body.', // 🗒️ Plain text content
    attachment: [{ data: 'Hello!' }], // 📎 One or more attachments
};

Message#attach(options)

Adds an attachment to the message. Can be called multiple times.

message.attach({
    path: 'path/to/file.zip', // 📁 Path to a file on disk
    data: 'Binary content as string or buffer', // 📄 Raw data
    stream: fs.createReadStream('file.jpg'), // 🌊 A readable stream
    type: 'application/zip', // MIME type
    name: 'custom-name.zip', // Filename perceived by recipient
    alternative: true, // attach inline as an alternative (e.g., HTML body)
    inline: true, // If true, attached inline (e.g., for <img src="cid:...">)
    headers: { 'X-Custom-Header': 'value' }, // Custom attachment headers
});

Message#checkValidity()

Synchronously validates that a Message is properly formed before sending.

const { isValid, validationError } = message.checkValidity();
if (!isValid) {
    console.error('Message is invalid:', validationError);
}

Authors ✍️

  • eleith
  • zackschuster

Testing 🧪

# Run all tests
npm test

# Run tests with code coverage report
npm run test:coverage

Development 🧑‍💻🌱

for a local smtp testing experience, use our Mailpit compose service

1. Start Mailpit with Docker Compose

Ensure you have Docker and Docker Compose installed.

# From the project root, start Mailpit
docker compose up

Mailpit will be accessible via:

  • Web UI: http://localhost:8025
  • SMTP Server: localhost:1025

2. Run Example Sending Scripts

You can use the provided scripts to send different types of emails to your local Mailpit instance.

First, make sure the emailjs library is built:

npm run build

Then, run any of the example scripts:

# Send a plain text email
node scripts/send-text.js

# Send an HTML email
node scripts/send-html.js

# Send an email with attachments
node scripts/send-attachment.js

After running a script, open your Mailpit Web UI (http://localhost:8025) to see the emails stream in! 📩

更新日志

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog and this project adheres to Semantic Versioning.

[5.0.0] - 2025-12-12

Added

  • Added docker-compose.yml to run mailpit for manual end-to-end testing.
  • Added test emails in scripts/ to be run agains mailpit.
  • Increased test coverage

Migrated

  • Migrated project to latest TypeScript (v5.x) with strict typing.
  • Migrated all tests from AVA to Vitest.
  • Refactored project structure to src/ for source code and co-located tests.

Changed

  • Updated core dependencies to their latest versions.
  • Updated tsconfig.json and adopted tsc for builds.
  • Updated ESLint and Prettier configurations.

Removed

  • AVA testing framework and its associated configurations.
  • Rollup build system and its configurations.
  • Removed JSDoc comments.
  • Legacy source files and build artifacts (email.js, email.ts, smtp/ directory).
  • Dropped legacy dual support (CommonJS/ESM) in favor of the latest Node.js standards.

[4.0.2] - 2023-05-12

Fixed

  • redact passwords in error messages #339

[4.0.0] - 2022-04-20

Added

  • support isolatedModules and preserveValueImports compilation scenarios #305

Fixed

  • support typescript@3.8.3 #307
    • the types change in v3.8.0 for Client#send & Client#sendAsync unintentionally raised the minimum typescript requirement. fixing this involved weakening the types for those functions, which may require modifying your code. this change will be reverted for v4.0.0.

[3.8.0] - 2022-03-17

Added

  • support typescript@4.6
  • type allow Client#send & Client#sendAsync to accept message headers instead of a Message
    • no behavior change: this was previously allowed, but the types didn't acknowledge it

[3.7.0] - 2021-11-19

Added

  • support typescript@4.5

[3.6.0] - 2021-09-03

Added

  • support tsc compilation without --esModuleInterop or --allowSyntheticDefaultImports #296
  • Message#readAsync API #297
  • Message#checkValidity API #298

Deprecated

  • Message#valid API #298

[3.5.0] - 2021-06-28

Added

  • support tsc --noPropertyAccessFromIndexSignature #290

Fixed

  • use engines field in package.json to signal node version support

[3.4.0] - 2020-12-01

Added

  • SMTPClient#sendAsync API #267
  • isRFC2822Date API

Changed

  • use WeakSet instead of WeakMap for greylist tracking

Fixed

  • use camelCase style for internal function names
  • use correct types in jsdoc comments

[3.3.0] - 2020-08-08

Added

  • greylist support #202

Fixed

  • check socket is writable before sending #205

[3.2.1] - 2020-06-27

Fixed

  • use correct type for MessageAttachment.stream #261
  • add missing types in mime functions #262

[3.2.0] - 2020-06-19

Added

  • addressparser API (forked from dropped dependency) #259
  • mimeEncode/mimeWordEncode APIs (forked from dropped dependency) #247

Changed

  • drop dependency on addressparser #259
  • drop dependency on emailjs-mime-codec #247

Fixed

  • make MessageAttachment interface usable #254
  • mend regression in address type validation #252

[3.1.0] - 2020-06-19 [YANKED]

[3.0.0] - 2020-05-28

Added

  • convert source to strict typescript, listed under the types field in package.json
  • support "dual-package" ESM + CJS via conditional exports & rollup-generated bundles
  • SMTPClient#creatMessageStack API #229
  • SMTPError API

Changed

  • simplify public API #249
  • rename Client -> SMTPClient #249
  • rename SMTPResponse -> SMTPResponseMonitor #249

Removed

  • Message#attach_alternative API
  • makeSMTPError API

Fixed

  • filter duplicate message recipients #242
  • error when passing password without user #199
  • trim host before connecting #136

[2.2.0] - 2018-07-06

Added

  • expose rfc2822 date module
  • annotate code with typescript-compatible jsdoc tags

Changed

  • drop dependency on moment
  • drop dependency on starttls

Fixed

  • ensure timeout is set to default value #225

[2.1.0] - 2018-06-09

Added

  • expose error module

Changed

  • handle errors with fs.closeSync instead of fs.close
  • refactor to ES2015+ constructs
  • lint & format with eslint + prettier
  • drop optional dependency on bufferjs

Fixed

  • remove new Buffer calls

[2.0.1] - 2018-02-11

Added

  • a new changelog