I am trying to create a form that will send data to the Mongo DB first then will send that data through the email by Nodemailer. Here are the 2 functions:
contro
Export your sendMail method and import it in your controller.
controller function
let sendMail = require('your nodemailer file').sendMail;
exports.createListing = (req, res) => {
// Validate request
if(!req.body.content) {
return res.status(400).send({
message: "Fields can not be empty"
});
}
const listing = new Listing({
title: req.body.title,
city: req.body.city,
street: req.body.street,
businessname: req.body.businessname,
description: req.body.description
});
listing.save()
.then(data => {
sendMail({
title: req.body.title,
city: req.body.city,
street: req.body.street})
res.send(data);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while creating the listing."
});
});
};
NodeMailer function
var smtpTransport = nodemailer.createTransport({
service: 'Gmail',
port: 465,
auth: {
user: 'YOUR_GMAIL_SERVER',
pass: 'YOUR_GMAIL_PASSWORD'
}
});
module.exports.sendmail = (data)=>{
return new Promise((resolve,reject)=>{
var mailOptions = {
to: data.email,
subject: 'ENTER_YOUR_SUBJECT',
html: `${data.title}
${data.city}
${data.street}
`,
...
};
smtpTransport.sendMail(mailOptions,
(error, response) => {
if (error) {
reject(error);
} else {
resolve('Success');
}
smtpTransport.close();
});
});
};