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
I would suggest creating a wrapper module around nodemailer, therefore you could reuse the sendEmail
function multiple times.
Make yourself a file called email-client.js
or whatever you want. In this module, you can create a closure over smtpTransport
and only export the sendEmail
function.
email-client
const nodemailer = require("nodemailer");
const smtpTransport = nodemailer.createTransport({
service: "Gmail",
port: 465,
auth: {
user: "YOUR_GMAIL_SERVER",
pass: "YOUR_GMAIL_PASSWORD"
}
});
async function sendMail({ to, subject, html }) {
return smtpTransport.sendMail({ to, subject, html });
}
module.exports = {
sendMail
};
Note: smtpTransport.sendMail
returns a Promise, that we will deal with inside your controller.
controller
First, you could import the sendEmail
function that's exported from email-client.js
, then you can use this in your controller. Note ive changed the controller to be async & prefer mongoose Model.create (makes testing a little easier).
const { sendEmail } = require("./email-client.js");
exports.createListing = async (req, res) => {
try {
if (!req.body.content) {
return res.status(400).send({
message: "Fields can not be empty"
});
}
const listing = await Listing.create({
title: req.body.title,
city: req.body.city,
street: req.body.street,
businessname: req.body.businessname,
description: req.body.description
});
await sendEmail({
to: "blabla",
subject: "blabla",
html: `${listing.title}
${listing.city}
${listing.street}
`
});
return res.send("Success");
} catch (error) {
return res.status(500).send({
message:
error.message ||
"Some error occurred while creating the listing."
});
}
};