DailyJS

Node Tutorial Part 14: Email

Alex R. Young

Subscribe

@dailyjs

Facebook

Google+

tutorials server node email lmawa nodepad express

Node Tutorial Part 14: Email

Posted by Alex R. Young on .
Featured

tutorials server node email lmawa nodepad express

Node Tutorial Part 14: Email

Posted by Alex R. Young on .

Welcome to part 14 of Let's Make a Web App, a tutorial series about
building a web app with Node. This series will
walk you through the major areas you'll need to face when building your
own applications. These tutorials are tagged with
lmawa.

Previous tutorials:

Email

Nodepad should send customer support emails -- sign up notifications,
password resets -- that kind of thing. So far I haven't touched on email
in this tutorial series, but it's required by most web applications.

Node already has a few SMTP libraries and the two most active ones have
very similar APIs and names. I have no particular preference because I
haven't done anything complicated with them. If you have in-depth
experience with SMTP and Node, readers may enjoy to hear from you in the
comments.

I've decided to use node_mailer
by Marak Squires. It can be installed with npm:

npm install mailer@0.4.52

As of today, mailer is at version 0.4.52. I've updated Nodepad's
package.json and the app.js require to reflect this.

SMTP API

Sending an email looks like this:

var mailer = require('mailer');

mailer.send({
    // node_mailer supports authentication,
    // docs at: https://github.com/marak/node_mailer
    host:    'localhost',
    port:    '25',
    to:      'alex@example.com',
    from:    'nodepad@example.com',
    subject: 'Welcome to Nodepad',
    body:    'All work and no play makes DailyJS pretty dull'
  },

  // Your response callback
  function(err, result) {
    if (err) {
      console.log(err);
    }
  }
);

If you've got a local SMTP daemon running, this code should work. Of
course, you'll need to change the to parameter to actually receive an
email.

Development Mode

I thought it would be wise to only send mails when running in production
mode, and I wanted to render mails using Jade. My example will be a
plain text email for now, but using Jade should simplify HTML emails
later.

The mail settings can be put in the app.configure function:

app.configure(function() {
  app.set('mailOptions', {
    host:    'localhost',
    port:    '25',
    from:    'nodepad@example.com',
  });
  // ... snip ...

You could override this with development and production email server
settings.

Simulating SMTP Locally

By the way, node_mailer comes bundled with stubSMTP. This
script will allow you to receive mails and view them. The results look
like this: