Git Product home page Git Product logo

node-email-templates's Introduction

node-email-templates Build Status NPM version

Node.js module for rendering beautiful emails with your template engine and CSS pre-processor of choice coupled with email-friendly inline CSS using juice.

Follow @niftylettuce on Twitter for updates.

Like this module? Check out express-cdn!

The Rebel's Guide to Email Marketing Modern HTML Email Email Marketing By the Numbers

Index

Email Templates

For professional and customizable email templates, please visit https://github.com/mailchimp/Email-Blueprints.

Supported Template Engines

Supported CSS Pre-processors

Prerequisites

This module depends on jsdom which requires the ability to compile C++ on your localhost. Before installing, please verify that you have the prerequisites installed for your OS.

Windows Users

Developing on osx/linux is recommended but if you only have access to a Windows machine you can either:

  1. Use vagrant to create a linux dev environment (recommended)
  2. Follow the Windows installation guide for contextify

Installation

npm install email-templates

NOTE: Starting with version 1.1.1 you must install the engines you wish to use, add them to your package.json dependencies.

npm install <your template-engine [ejs|jade|swig|handlebars|emblem|dust-linkedin]>

Quick Start

  1. Install the module for your respective project npm install email-templates
  2. Install the template engine you intend to use npm install ejs or npm install jade or any other of the above mentioned.
  3. Create a folder called templates inside your root directory (or elsewhere).
  4. For each of your templates, respectively name and create a folder inside the templates folder.
  5. Add the following files inside the template's folder:
    • html.{{template engine}} - See supported template engines (required)
    • text.{{template engine}} - See supported template engines (optional)
    • style.{{CSS pre-processor}} - See supported CSS pre-processors (optional)
    • NEW: You may prefix any file name with anything you like to help you identify the files more easily in your IDE. The only requirement is that the filename contains html., text., and style. respectively.
  6. You may use the include directive from ejs (for example, to include a common header or footer). See the /examples folder for details.
  7. Utilize one of the examples below for your respective email module and start sending beautiful emails!

Template Engine Options

If your want to configure your template engine, just pass options.

Want to use different opening and closing tags instead of the EJS's default <% and %>?.

...
emailTemplates(templatesDir, { open: '{{', close: '}}' }, function(err, template) {
...

NOTE: You can also pass other options from EJS's documentation.

Want to add a helper or partial to Handlebars?

...
emailTemplates(templatesDir, {
  helpers: {
    uppercase: function(context) {
      return context.toUpperCase()
    }
  }, partials: {
    ...
  }
})
...

Examples

Basic

Render a template for a single email or render multiple (having only loaded the template once).

var path           = require('path')
  , templatesDir   = path.join(__dirname, 'templates')
  , emailTemplates = require('email-templates');

emailTemplates(templatesDir, function(err, template) {

  // Render a single email with one template
  var locals = { pasta: 'Spaghetti' };
  template('pasta-dinner', locals, function(err, html, text) {
    // ...
  });

  // Render multiple emails with one template
  var locals = [
    { pasta: 'Spaghetti' },
    { pasta: 'Rigatoni' }
  ];
  var Render = function(locals) {
    this.locals = locals;
    this.send = function(err, html, text) {
      // ...
    };
    this.batch = function(batch) {
      batch(this.locals, this.send);
    };
  };
  template('pasta-dinner', true, function(err, batch) {
    for(var user in users) {
      var render = new Render(users[user]);
      render.batch(batch);
    }
  });

});
var path           = require('path')
  , templatesDir   = path.resolve(__dirname, '..', 'templates')
  , emailTemplates = require('email-templates')
  , nodemailer     = require('nodemailer');

emailTemplates(templatesDir, function(err, template) {

  if (err) {
    console.log(err);
  } else {

    // ## Send a single email

    // Prepare nodemailer transport object
    var transport = nodemailer.createTransport("SMTP", {
      service: "Gmail",
      auth: {
        user: "[email protected]",
        pass: "some-password"
      }
    });

    // An example users object with formatted email function
    var locals = {
      email: '[email protected]',
      name: {
        first: 'Mamma',
        last: 'Mia'
      }
    };

    // Send a single email
    template('newsletter', locals, function(err, html, text) {
      if (err) {
        console.log(err);
      } else {
        transport.sendMail({
          from: 'Spicy Meatball <[email protected]>',
          to: locals.email,
          subject: 'Mangia gli spaghetti con polpette!',
          html: html,
          // generateTextFromHTML: true,
          text: text
        }, function(err, responseStatus) {
          if (err) {
            console.log(err);
          } else {
            console.log(responseStatus.message);
          }
        });
      }
    });


    // ## Send a batch of emails and only load the template once

    // Prepare nodemailer transport object
    var transportBatch = nodemailer.createTransport("SMTP", {
      service: "Gmail",
      auth: {
        user: "[email protected]",
        pass: "some-password"
      }
    });

    // An example users object
    var users = [
      {
        email: '[email protected]',
        name: {
          first: 'Pappa',
          last: 'Pizza'
        }
      },
      {
        email: '[email protected]',
        name: {
          first: 'Mister',
          last: 'Geppetto'
        }
      }
    ];

    // Custom function for sending emails outside the loop
    //
    // NOTE:
    //  We need to patch postmark.js module to support the API call
    //  that will let us send a batch of up to 500 messages at once.
    //  (e.g. <https://github.com/diy/trebuchet/blob/master/lib/index.js#L160>)
    var Render = function(locals) {
      this.locals = locals;
      this.send = function(err, html, text) {
        if (err) {
          console.log(err);
        } else {
          transportBatch.sendMail({
            from: 'Spicy Meatball <[email protected]>',
            to: locals.email,
            subject: 'Mangia gli spaghetti con polpette!',
            html: html,
            // generateTextFromHTML: true,
            text: text
          }, function(err, responseStatus) {
            if (err) {
              console.log(err);
            } else {
              console.log(responseStatus.message);
            }
          });
        }
      };
      this.batch = function(batch) {
        batch(this.locals, templatesDir, this.send);
      };
    };

    // Load the template and send the emails
    template('newsletter', true, function(err, batch) {
      for(var user in users) {
        var render = new Render(users[user]);
        render.batch(batch);
      }
    });

  }
});

This example utilizes Postmark.js.

NOTE: Did you know nodemailer can also be used to send SMTP email through Postmark? See this section of their Readme for more info.

For more message format options, see this section of Postmark's developer documentation section.

var path           = require('path')
  , templatesDir   = path.resolve(__dirname, '..', 'templates')
  , emailTemplates = require('email-templates')
  , postmark       = require('postmark')('your-api-key');

emailTemplates(templatesDir, function(err, template) {

  if (err) {
    console.log(err);
  } else {

    // ## Send a single email

    // An example users object with formatted email function
    var locals = {
      email: '[email protected]',
      name: {
        first: 'Mamma',
        last: 'Mia'
      }
    };

    // Send a single email
    template('newsletter', locals, function(err, html, text) {
      if (err) {
        console.log(err);
      } else {
        postmark.send({
          From: 'Spicy Meatball <[email protected]>',
          To: locals.email,
          Subject: 'Mangia gli spaghetti con polpette!',
          HtmlBody: html,
          TextBody: text
        }, function(err, response) {
          if (err) {
            console.log(err.status);
            console.log(err.message);
          } else {
            console.log(response);
          }
        });
      }
    });


    // ## Send a batch of emails and only load the template once

    // An example users object
    var users = [
      {
        email: '[email protected]',
        name: {
          first: 'Pappa',
          last: 'Pizza'
        }
      },
      {
        email: '[email protected]',
        name: {
          first: 'Mister',
          last: 'Geppetto'
        }
      }
    ];

    // Custom function for sending emails outside the loop
    //
    // NOTE:
    //  We need to patch postmark.js module to support the API call
    //  that will let us send a batch of up to 500 messages at once.
    //  (e.g. <https://github.com/diy/trebuchet/blob/master/lib/index.js#L160>)
    var Render = function(locals) {
      this.locals = locals;
      this.send = function(err, html, text) {
        if (err) {
          console.log(err);
        } else {
          postmark.send({
            From: 'Spicy Meatball <[email protected]>',
            To: locals.email,
            Subject: 'Mangia gli spaghetti con polpette!',
            HtmlBody: html,
            TextBody: text
          }, function(err, response) {
            if (err) {
              console.log(err.status);
              console.log(err.message);
            } else {
              console.log(response);
            }
          });
        }
      };
      this.batch = function(batch) {
        batch(this.locals, templatesDir, this.send);
      };
    };

    // Load the template and send the emails
    template('newsletter', true, function(err, batch) {
      for(user in users) {
        var render = new Render(users[user]);
        render.batch(batch);
      }
    });

  }
});

Lazyweb Requests

These are feature requests that we would appreciate contributors for:

  • Rewrite this module to have a more modular API (e.g. template caching and email queue support via kue)
  • Merge with @superjoe30 swig email templates fork
  • Add parsing of HTML with CSS inlining and HTML linting

Contributors

Full Contributors List

License

The MIT License

Copyright (c) 2012- Nick Baugh [email protected] (http://niftylettuce.com/)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

node-email-templates's People

Contributors

niftylettuce avatar jasonsims avatar jeduan avatar jasminetsai avatar nicjansma avatar skimmmer avatar rblu avatar vekexasia avatar bratchenko avatar dchymko avatar jonkemp avatar designbyonyx avatar antoinepairet avatar jksdua avatar

Watchers

James Cloos avatar  avatar Ivan Rigamonti avatar Boris Wechselberger avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.