Skip to main content

Plugins

Nodemailer is designed to be extensible. You can inject custom logic at three well-defined phases of a message's lifecycle:

PhaseKeywordWhen it runsTypical uses
Pre-processingcompileAfter the message object is created but before the MIME source is generatedTemplating, automatic plain-text alternatives, address validation
ProcessingstreamAfter MIME compilation, while the message stream is being prepared for sendingInlining images, transforming HTML content
SendingtransportWhen the message is ready to be deliveredSMTP, SES, SparkPost, custom HTTP APIs
tip

Use compile and stream plugins when you want your plugin to work with any transport. Transport plugins are only needed when you want to define a completely custom delivery mechanism.

Writing a plugin

A plugin is a function that receives a mail object and a callback. Here is an example that automatically generates a plain-text version of your email when only HTML is provided:

// CommonJS module format
module.exports = function myCompilePlugin(mail, callback) {
// The mail object contains a `data` property with your message options
// You can read and modify these properties before the message is compiled

if (!mail.data.text && mail.data.html) {
// Generate plain-text from HTML using the html-to-text package
mail.data.text = require("html-to-text").htmlToText(mail.data.html);
}

// Always call the callback when done
// Pass no arguments for success, or pass an Error to abort sending
callback();
};

To use the plugin, register it on a transport instance with the use() method:

const nodemailer = require("nodemailer");
const transport = nodemailer.createTransport({ sendmail: true });

// Register a compile plugin - it will run before MIME generation
transport.use("compile", require("./myCompilePlugin"));

Error handling

If your plugin encounters a problem that should prevent the message from being sent, pass an Error object to the callback:

callback(new Error("Template not found"));

When you pass an error, the message will not be sent. The error will be returned to the caller through the sendMail() callback or rejected promise.

Public plugins

Here are some popular community-maintained plugins you can use:

Looking for something else? Try searching npm for "nodemailer plugin".


Need more control? See Creating plugins for a detailed guide on the plugin API.