V
V
Valery Orlov2018-08-28 16:05:43
Node.js
Valery Orlov, 2018-08-28 16:05:43

How to check if 'nodemailer' sent email successfully?

When a user registers, I send him a notification by e-mail. For this I use the 'nodemailer' module. How can I make app.js check the condition when calling mailer: If the mail was successfully sent, do res.send('Registration was successful') ?
App.js code:

const express  = require('express');
var app = express();
const mailer  = require('../app/module/sendmail');
const port     = process.env.PORT || 8000;

app.post('/signup, function (req, res) {
  mailer('[email protected]', 'passwd');
})

app.listen(port);
console.log('NodeJS слушает порт: ' + port);

Below is the Sendmail.js module code:
const nodemailer = require('nodemailer');
const morgan = require("morgan");

var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: process.env.GMAIL_USER,               
    pass: process.env.GMAIL_PASS
  }
});

module.exports = function(email, passwd){
var mailOptions = {
  from: process.env.GMAIL_USER,
  to: email,
  subject: 'Благодарим за регистрацию',
  html: `<p>Вы успешно зарегистрированы!</p>
         <p>Ваш логин: <b>${email}</b><br>
         Пароль: <b>${passwd}</b></p>`
};

transporter.sendMail(mailOptions, function(error, info){
  if(error){
    console.log('Ошибка отправки на почту извещения');
  } else {
    console.log('Обработанно');
  }
});
}

The validation should work in app.js, not in the included module Sendmail.js.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaly, 2018-08-28
@vitali1995

Easy option: declare transporter inside the express handler.
The correct option is to promissify sendMail, i.e. wrap in a function that returns a promise that can be subscribed to from the outside.

function sendMail(mailOptions) {
  return new Promise((resolve, reject) =>
    transporter.sendMail(mailOptions, (error, info) => {
      if(error){
        reject(error);
      } else {
        resolve(info);
      }
    });
  });
}

Using Promises:
sendMail(mailOptions)
  .then(info => console.log(info))
  .catch(error => console.error(error));

or like this:
try {
  const info = await sendMail(mailOptions);
  console.log(info);
} catch (error) {
  console.error(error);
}

R
RidgeA, 2018-08-28
@RidgeA

well, in `module.exports = function(email, passwd)` pass another callback, which is called upon sending the message....
Better yet, switch to promises....

S
SagePtr, 2018-08-28
@SagePtr

It is best not to rely on such verification. The letter can leave safely, but still be destroyed somewhere along the way. This fact cannot be verified.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question