0

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.

user3440787
  • 193
  • 3
  • 11
  • 1
    nodemailer is async - call it with `await` – Darth Nov 12 '20 at 09:39
  • 1
    you can return a promise from your sendMail function and transform your code to sendMail('Server is shutting down").then(()=> process.exit()) – phoenixstudio Nov 12 '20 at 09:41
  • `nodemailer transporter.sendMail` takes a callback by default. You can modify your `sendMail function` by taking a callback. `function sendMail(msg, callback) {...}` and just pass the callback to your `transporter.sendMail(data, callback)`. That should do it, in my opinion. Your callback in this case would be `() => process.exit()`; – Rishabh Anand Nov 12 '20 at 09:45
  • Thanks @phoenixstudio it is working now. – user3440787 Nov 12 '20 at 09:57

1 Answers1

3

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)

phoenixstudio
  • 1,776
  • 1
  • 14
  • 19
  • I changed my sendMail() into to Promise and await the sendMail('Server is shutting down'); process.exit(); – user3440787 Nov 12 '20 at 10:09
  • Please note that if you remove process.exit(); your problem will also be solved, since even without using it (if all async function and callback are executed) the node process will exit, so the exit() is intendted to be used as a safty mesure to stop everything in case of an emergincy – phoenixstudio Nov 12 '20 at 10:18