Search code examples
node.jsnodemailer

How to send email before process.exit() in NodeJS?


I need to send an email when server is shutting down, I'm using nodemailer but email is not sending when I write it before process.exit().

sendMail('Server is shutting down')
process.exit();

I was trying to use "beforeExit" event but it's not working either.

The 'beforeExit' event is not emitted for conditions causing explicit termination, such as calling process.exit() or uncaught exceptions.

As I understand as per the Doc.

Listener functions must only perform synchronous operations. The Node.js process will exit immediately after calling the 'exit' event listeners causing any additional work still queued in the event loop to be abandoned. In the following example, for instance, the timeout will never occur:

process.on('exit', (code) => {
  setTimeout(() => {
    console.log('This will not run');
  }, 0);
}); 

On exit event it requires a sync call but nodemailer is async.


Solution

  • Node mail has a callback mechanism transporter.sendMail(data[, callback]), you can transfome that to a Promise then you you will be able to do this in your code:

    sendMail('Server is shutting down')
    .then(()=>{ 
      process.exit();
    })
    

    or you can add and await by transforming you function to an async function as a results for one of the two solution process.exit(); will be called only after the sendMail function callback has excuted (=mail added to the queue of Postfix for example)