Answer the question
In order to leave comments, you need to log in
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);
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('Обработанно');
}
});
}
Answer the question
In order to leave comments, you need to log in
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);
}
});
});
}
sendMail(mailOptions)
.then(info => console.log(info))
.catch(error => console.error(error));
try {
const info = await sendMail(mailOptions);
console.log(info);
} catch (error) {
console.error(error);
}
well, in `module.exports = function(email, passwd)` pass another callback, which is called upon sending the message....
Better yet, switch to promises....
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question