Nodejitsu

Save time managing and deploying your node.js app. Code faster with jitsu and npm

sending emails in node

About the author

Name
Location
Worldwide
nodejitsu nodejitsu

Sending emails is a classic software development problem. At some point, your application will need to send an email to someone. node.js has the ability to open arbitrary tcp sockets, so with node_mailer, we can easily connect to an existing SMTP server and start sending out emails.


First, you need to install the node_mailer. You can find the installation instructions here: https://github.com/Marak/node_ mailer. Once you have node_mailer installed it's really easy to start blasting emails from your node.js scripts.

var email = require('mailer');

email.send({  
  host : "localhost",              // smtp server hostname
  port : "25",                     // smtp server port
  domain : "localhost",            // domain used by client to identify itself to server
  to : "marak.squires@gmail.com",
  from : "obama@whitehouse.gov",
  subject : "node_mailer test email",
  body: "Hello! This is a test of the node_mailer.",
  authentication : "login",        // auth login is supported; anything else is no auth
  username : "dXNlcm5hbWU=",       // Base64 encoded username
  password : "cGFzc3dvcmQ="        // Base64 encoded password
},
function(err, result){  
  if(err){ console.log(err); }
});

This snippet assumes you have a locally running SMTP server. sendmail is a decent choice for a local SMTP server, but you can't exactly just start firing off emails from any server or machine and expect it not to go straight into your user's spam box.

Modern email providers such as Gmail or Yahoo Mail have spam filters which will flag any sketchy looking emails. If you try to send email from a random home connection or Virtual Private Server, it will probably go straight into the spam box. Setting up a proper SMTP server with things such as SPF records is not exactly trivial.


You want to build an application, not manage an email server!

Fortunately, there are services which provide trusted SMTP servers, such as sendgrid. Using sendgrid we can easily connect to a remote SMTP server and begin pumping out emails. Once you are using a SMTP that is not on your localhost, you will most likely need to use some sort of authorization. luckily, node_mailer supports basic authentication!

var email = require('mailer');

email.send({  
  host: "smtp.sendgrid.net",
  port : "25",
  domain: "smtp.sendgrid.net",
  authentication: "login",
  username: (new Buffer("myAccountName")).toString("base64"),
  password: (new Buffer("myPassword")).toString("base64"),
  to : "marak.squires@gmail.com",
  from : "test@mydomain.com",
  subject : "node_mailer test email",
  body : "hello this a test email from the node_mailer",
  function(err, result){
    if(err){ console.log(err); }
  });

But wait! Let's do some templating!

If you want to start sending more then a simple body for the email, you are going to start collecting some gnarly string concatenation statements in your email.send() code. Fortunately, as of version 0.4.0, node_mailer supports basic JSON replacement Mustache templating!

First, create your sampleTemplate.txt

Hello {{username}}, 

This is a sample template of the node mailer.

It uses mustache templating to do basic search and replaces. 

The {{color}} {{animal}} {{adjective}} ran over the {{noun}}.  

Then, call email.send() using the following syntax:

var email = require("./lib/node_mailer");

email.send({  
  host : "localhost",              // smtp server hostname
  port : "25",                     // smtp server port
  domain : "localhost",            // domain used by client to identify itself to server
  to : "marak.squires@gmail.com",
  from : "obama@whitehouse.gov",
  subject : "node_mailer test email",
  template : "sampleTemplate.txt",   // path to template name
  data : {
    "username": "Billy Bob",
    "color": function(){
      var arr = ["purple", "red", "green", "yello"];
      return arr[Math.floor(Math.random()*3)];
    },
    "animal": "monkey",
    "adjective": "quickly",
    "noun": "hot lava"
  },

  authentication : "login",        // auth login is supported; anything else is no auth
  username : "dXNlcm5hbWU=",       // Base64 encoded username
  password : "cGFzc3dvcmQ="       // Base64 encoded password
},
function(err, result){  
  if(err){ console.log(err); }
});

Your email body will now look something like this:

Hello Billy Bob,  
This is a sample template of the node mailer.  
It uses mustache templating to do basic search and replaces.  
The red monkey quickly ran over the hot lava.  

Huzaah! There you go! node_mailer is open-source, so lets get hacking!