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
Add email.js file to api folder Just Open http://localhost:3000/api/email this link in browser and you can see Json Out Put on Screen. import { SMTPClient } from 'emailjs'; Than We have to create client object by passing you email and password.
Create a new account with the email address you want to use as the sender. Once your account is created, click on the “Create a Single Sender” button. If you don't see the button below, you can also find this in Settings -> Sender Authentication. Fill out the required fields in the “Create a Sender” form.
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");
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With