Search code examples
node.jsasync-awaitnodemailer

nodemailer sendEmail doesn't wait in Node.js


When I make a request to my endpoint I need to get a successful response only if the email is sent! otherwise, it should throw an error:

myendpoint.js

    router.post("/", upload.none(), async (req, res) => {
    try {
    let body = JSON.parse(req.body.contact);

    await getDb("messages").insertOne({
      name: body.name,
      email: body.email,
      phone: body.phone,
      subject: body.subject,
      message: body.message,
    });

    await sendEmail(body);

    res.send(
      JSON.stringify({
        success: true,
        msg: "Message has been sent successfully",
      })
    );
  } catch (err) {
    res.send(JSON.stringify({ success: false, msg: err }));
  }
});

sendEmail.js

    const sendEmail = async function (props) {
    const transporter = nodemailer.createTransport({
    service: process.env.EMAIL_SERVICE,
    host: process.env.EMAIL_HOST,
    auth: {
      user: process.env.EMAIL_FROM,
      pass: process.env.EMAIL_PASS,
    },
  });
  const mailOptions = {
    from: process.env.EMAIL_FROM,
    to: process.env.EMAIL_TO,
    name: props.name,
    email: props.email,
    phone: props.phone,
    subject: props.subject,
    text: props.message,
  };
  transporter.sendMail(mailOptions, function (error, info) {
    if (error) {
      throw new Error("Message did Not send!");
    }
  });
};

the problem is before "await sendEmail(body);" ends and i get the error, i get the "Message has been sent successfully" and then server crashes! what am i missing?


Solution

  • Hello you can change your Transporter sendMail to :

    return await transporter.sendMail(mailOptions);
    

    Or You can Use Promise.