Search code examples
javascriptnode.jsgmailnext.jsnodemailer

Next.JS and Nodemailer, Sending an email from contact form


I have a problem with my contact form in next.js, I don't have any errors (that are shown), everything worked untill deployment (on Vercel). I fetch my form, and have status 200, but I do not recive my email on Gmail. Also I don't recive any additional information. I've recived emails, when I tested my app on "dev" and "build". I've also have "less secure apps" option in Gmail account.

Here's my code in Next.JS:

fetch method in contact.js:

 fetch("/api/contact", {
        method: "POST",
        headers: {
          Accept: "application/json, text/plain, */*",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          name: mailName,
          email: mailAddress,
          text: mailText,
        }),
      }).then((res) => {
        console.log("Fetch: ", res);
        res.status === 200
        ?
        router.push("/success")
          : router.push("/error");

in api/contact.js

require("dotenv").config();
const nodemailer = require("nodemailer");

export default (req, res) => {

  const { name, email, text } = req.body;

  const transporter = nodemailer.createTransport({
    service: "gmail",
    auth: {
      user: process.env.EMAIL,
      pass: process.env.PASSWORD,
    },
  });

  const mailOption = {
    from: `${email}`,
    to: `${process.env.EMAIL}`,
    subject: `New mail from ${email}`,
    text: `
    ${name} wrote:
    ${text}
    `,
  };

  transporter.sendMail(mailOption, (err, data) => {
    if (err) {
      console.log(err);
    } else {
      console.log("mail send");
    }
  });

  console.log(name, email, text);
  res.send("success");
};

Please help


Solution

  • Since your code runs fine in local and not in the deployment environment I have two suggestions.

    First, make sure you have all the environment variables set.

    Secondly, the way you have written your code it will always return success because transporter.sendMail is asynchronous and res.send is outside of it.

    Change like,

    transporter.sendMail(mailOption, (err, data) => {
        if (err) {
          console.log(err);
          res.send("error" + JSON.stringify(err));
        } else {
          console.log("mail send");
          res.send("success");
        }
    });