// components/forms/ContactSeller.js
const handleSubmit = async () => {
if (auth.user === null && auth.token === "") {
navigate("/login", {
state: `/ad/${ad.slug}`,
});
}
setLoading(true);
try {
// console.log(name, email, message, phone);
const { data } = await axios.post("/contact-seller", {
name,
email,
message,
phone,
adId: ad._id,
});
if (data?.error) {
toast.error(data.error);
setLoading(false);
} else {
toast.success("Thank you for your enquiry");
setLoading(false);
}
} catch (err) {
console.log(err);
setLoading(false);
toast.error("Something went wrong. Try again.");
}
};
Create route and controller function to send email
// routes/ad
router.post("/contact-seller", ad.contactSeller);
// controllers/ad
export const contactSeller = async (req, res) => {
try {
const { name, email, message, phone, adId } = req.body;
const user = await User.findOneAndUpdate(
{ email },
{
$addToSet: { enquiredProperties: adId },
}
);
const ad = await Ad.findById(adId).populate("postedBy", "email");
if (!user) {
res.json({ error: "Could not find user with that email" });
} else {
// send email
config.AWSSES.sendEmail(
emailTemplate(
ad.postedBy.email,
`
<p>You have received a new customer enquiry.</p>
<h4>Customer details</h4>
<p>Name: ${name}</p>
<p>Email ${email}</p>
<p>Phone: ${phone}</p>
<p>Message: ${message}</p>
<p>Enquiried property:</p>
<a href="${config.APP_NAME}/ad/${ad.slug}">${ad?.type} in ${ad?.address} for ${ad?.action} $${ad?.price}</a>
`,
email,
"New enquiry received"
),
(err, data) => {
if (err) {
return res.json({ error: "Provide a valid email address" });
} else {
return res.json({ success: "Check email to access your account" });
}
}
);
}
} catch (err) {
console.log(err);
res.json({ error: "Something went wrong. Try again." });
}
};