What is correct way of using Nodemailer in expressjs?

Yalamber picture Yalamber · Jan 14, 2014 · Viewed 10k times · Source

I am trying to use nodemailer in expressjs app. Should I keep creating of transport object out of route handler or creating transport object inside route handler is just fine?

var express = require('express')
  , app = express()
  , nodemailer = require('nodemailer');

  smtpTrans = nodemailer.createTransport('SMTP', {
      service: 'Gmail',
      auth: {
          user: "[email protected]",
          pass: "application-specific-password" 
      }
  });
  app.post('/register', function(req, res){
    smtpTrans.sendMail(mailOptions);
  });

or

var express = require('express')
  , app = express()
  , nodemailer = require('nodemailer');

  app.post('/register', function(req, res){
    smtpTrans = nodemailer.createTransport('SMTP', {
      service: 'Gmail',
      auth: {
          user: "[email protected]",
          pass: "application-specific-password" 
      }
    });
    smtpTrans.sendMail(mailOptions);
  });

Answer

Paul Mougel picture Paul Mougel · Jan 14, 2014

You have to think about your use case to make a choice.

The SMTP transport in nodemailer creates a connection pool that you explicitly have to close. This is good because the connection always stays open: you only suffer the connection delays (including TLS negotiation, etc.) when the app starts up.

Your first solution is then good if you send a lot of messages: by keeping a connection open you'll minimize the delay and resource utilization by using the connection pool.

On the other hand, your second solution is good if you send few messages: there's no need to maintain a connection if you send one email per hour. Be careful, as your current code is a bit wrong: you need to explicitly close the connection pool. If you don't, the connection pool will stay open even if you loose the reference to the object.

smtpTrans = nodemailer.createTransport('SMTP', { … });
smtpTrans.sendMail(mailOptions, function (err, responseStatus) {
  smtpTrans.close(); // Don't forget to close the connection pool!
});

From the looks of this issue, it seems that all errors are reported in the err parameter of the smtpTrans.sendMail callback.

Edit: This answer was written for Nodemailer 0.7. 1.0 is now out and has a few breaking changes, including on how it handles transports and connections. See this blog post for more information.