未找到nodemailer nextjs 14

问题描述 投票:0回答:1

即使我写了正确的路径“/api/sendEmail”,我也没有发现错误,它仍然返回 404 错误。 我正在使用 Nextjs 14、axios 和 nodemailer,我认为我做的一切都是正确的。 enter image description here enter image description here

next.js axios nodemailer
1个回答
0
投票
const onFinish = (values: any) => {
    const finalFormData = { ...formData, ...values };

    console.log("Final form data:", finalFormData);

    axios
      .post("http://localhost:1337/api/applicants", { data: finalFormData })
      .then((response) => {
        message.success("A candidatura foi submetida com sucesso");

        // After successful submission, send an email notification
        axios
          .post("/api/sendEmail", { finalFormData })
          .then((emailResponse) => {
            message.success("Email sent successfully");
          })
          .catch((emailError) => {
            console.error("Error sending email:", emailError);
            message.error("Error sending email");
          });
      })
      .catch((error) => {
        console.error("Error submitting the form:", error);
        message.error("Houve um erro ao submeter a candidatura");
      });
  };

-----
import nodemailer from "nodemailer";

export default async function handler(req: any, res: any) {
  if (req.method !== "POST") {
    res.setHeader("Allow", ["POST"]);
    return res.status(405).end(`Method ${req.method} Not Allowed`);
  }

  // Assuming you have SMTP_EMAIL and SMTP_PASSWORD set in your environment variables
  const transporter = nodemailer.createTransport({
    service: "gmail",
    auth: {
      user: process.env.SMTP_EMAIL,
      pass: process.env.SMTP_PASSWORD,
    },
  });

  const { finalFormData } = req.body;

  const mailOptions = {
    from: process.env.SMTP_EMAIL, // Use the email from environment variable
    to: "[email protected]",
    subject: "New Application Submission",
    text: `You've received a new application: ${JSON.stringify(finalFormData)}`,
  };

  try {
    // Verify transporter
    await transporter.verify();

    // Send email`enter code here`
    const info = await transporter.sendMail(mailOptions);
    console.log("Email sent: " + info.response);
    res.status(200).send("Email sent successfully");
  } catch (error) {
    console.error("Error sending email:", error);
    res.status(500).send("Error sending email");
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.