Sending Email with Nodemailer and node-mailer-templates

  1. Add Nodemailer and node-mailer-templates to your

    package.json file:

    package.json

       "email-templates": "0.0.5",
       "nodemailer": "0.3.x",
    
  2. Updated your dependencies

     npm install
    
  3. Create config settings for nodemailer in your config.js file

    config.js

     'use strict';
    
     module.exports = {
       db: {
         production: "mongodb://user:pass@example.com:1234/stroeski-prod",
         development: "mongodb://localhost/storeski-dev",
         test: "mongodb://localhost/storeski-test",
       },
       mailer: {
         auth: {
           user: 'test@example.com',
           pass: 'secret',
         },
         defaultFromAddress: 'First Last <test@examle.com>'
       }
     };
    
  4. Create a wrapper around the nodemailer module

    mailer/models.js

     'use strict';
    
     var config = require('../config');
     var nodemailer = require('nodemailer');
     var path = require('path');
     var templatesDir = path.resolve(__dirname, '..', 'views/mailer');
     var emailTemplates = require('email-templates');
    
     var EmailAddressRequiredError = new Error('email address required');
    
     // create a defaultTransport using gmail and authentication that are
     // stored in the `config.js` file.
     var defaultTransport = nodemailer.createTransport('SMTP', {
       service: 'Gmail',
       auth: {
         user: config.mailer.auth.user,
         pass: config.mailer.auth.pass
       }
     });
    
     exports.sendOne = function (templateName, locals, fn) {
       // make sure that we have an user email
       if (!locals.email) {
         return fn(EmailAddressRequiredError);
       }
       // make sure that we have a message
       if (!locals.subject) {
         return fn(EmailAddressRequiredError);
       }
       emailTemplates(templatesDir, function (err, template) {
         if (err) {
           //console.log(err);
           return fn(err);
         }
         // Send a single email
         template(templateName, locals, function (err, html, text) {
           if (err) {
             //console.log(err);
             return fn(err);
           }
           // if we are testing don't send out an email instead return
           // success and the html and txt strings for inspection
           if (process.env.NODE_ENV === 'test') {
             return fn(null, '250 2.0.0 OK 1350452502 s5sm19782310obo.10', html, text);
           }
           var transport = defaultTransport;
           transport.sendMail({
             from: config.mailer.defaultFromAddress,
             to: locals.email,
             subject: locals.subject,
             html: html,
             // generateTextFromHTML: true,
             text: text
           }, function (err, responseStatus) {
             if (err) {
               return fn(err);
             }
             return fn(null, responseStatus.message, html, text);
           });
         });
       });
     }
    
  5. Write a test to test sending an password reset email

    test/mailer/models.js

     'use strict';
    
     // import the mongoose helper utilities
     var utils = require('../utils');
     var should = require('should');
     var mailer = require('../../mailer/models');
    
     describe('mailer: models', function () {
    
       describe('#sendOne()', function (done) {
    
         it('should render the password reset templates correctly', function (done) {
           var locals = {
             email: 'one@example.com',
             subject: 'Password reset',
             name: 'Forgetful User',
             resetUrl: 'http;//localhost:3000/password_rest/000000000001|afdaevdae353'
           };
           mailer.sendOne('password_reset', locals, function (err, responseStatus, html, text) {
             should.not.exist(err);
             responseStatus.should.include("OK");
             text.should.include("Please follow this link to reset your password " + locals.resetUrl);
             html.should.include("Please follow this link to reset your password <a href=\"" + locals.resetUrl + "\">" + locals.resetUrl + "</a>");
             done();
           });
         });
       });
    
     });
    
  6. Create the templates:

    views/mailer/password_reset/text.ejs

     Please follow this link to reset your password <%= resetUrl %>
    

    views/mailer/password_reset/html.ejs

     Please follow this link to reset your password <a href="<%= resetUrl %>"><%= resetUrl %></a>
    

    Test are now passing:

     ✔ 15 tests complete (395 ms)
    

Resources

  • Nodemailer - Nodemailer is an easy to use module to send e-mails with Node.JS (using SMTP or sendmail or Amazon SES) and is unicode friendly - You can use any characters you like ✔
  • node-mailer-templates - Node.js module for rendering beautiful emails with ejs templates and email-friendly inline CSS using juice.

Comments