What is the correct way to use Nodemailer in expressjs?

I am trying to use nodemailer in an expressjs application. Should I continue to create the transport object outside the route handler or should I create the transport object inside the route handler, just fine?

var express = require('express') , app = express() , nodemailer = require('nodemailer'); smtpTrans = nodemailer.createTransport('SMTP', { service: 'Gmail', auth: { user: " me@gmail.com ", 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: " me@gmail.com ", pass: "application-specific-password" } }); smtpTrans.sendMail(mailOptions); }); 
+7
nodemailer
source share
1 answer

You must think about your use case in order to make a choice.

The SMTP transit to nodemailer creates a connection pool that you must explicitly close. This is good because the connection always remains open: you only suffer connection delays (including TLS negotiations, etc.) when the application starts.

Your first solution is then good if you send a lot of messages: by opening a connection, you minimize latency and resource use by using the connection pool.

On the other hand, your second solution is good if you send several messages: there is no need to maintain a connection if you send an email one hour. Be careful, as your current code is a bit wrong: you need to explicitly close the connection pool. If you do not, the connection pool will remain open, even if you lose 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! }); 

In appearance of this problem, it seems that all errors are reported in the err parameter of the smtpTrans.sendMail .

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

+7
source share

All Articles