skip to Main Content

I am using cpanel to host my next js website , and i have this api route that uses nodemailer to send messages, Any time i call the route i get Internal server error , but it works fine on localhost and even vercel
enter image description here

here is the api route => /api/mail

import { NextApiRequest, NextApiResponse } from "next";
import nodemailer from "nodemailer";

type Data = {
  message: string;
};

const handler = async (req: NextApiRequest, res: NextApiResponse<Data>) => {
  const message = {
    from: req.body.email,
    to: "[email protected]",
    subject: "New Customer Setup",
    text: `${req.body.email} ${req.body.firstname} ${req.body.lastname}`,
    html: `
    <p>Name: ${req.body.firstName} ${req.body.lastName}</p>
    <p>Email: ${req.body.email}</p>
    <p>Phone Number: ${req.body.mobileNumber}</p>
    <p>Residential Address: ${req.body.residentialAddress}</p>
    <p>Gender: ${req.body.gender?.value}</p>
    `,
  };

  const transporter = nodemailer.createTransport({
    secure: true,
    port: 465,
    host: "domain.com.ng",
    auth: {
      user: "[email protected]",
      pass: "pass",
    },
  });

  try {
    const info = await transporter.sendMail(message);
    console.log(info);
    res.status(200).json({
      message:
        "Thank you for your interest in domain. Our relationship agent will get back to you shortly.",
    });
  } catch (error:any) {
    console.error("Error sending email:", error);
    
    if (error.code === "ECONNREFUSED") {
      res.status(500).json({ message: "Failed to connect to the email server." });
    } else if (error.code === "EAUTH") {
      res.status(500).json({ message: "Invalid email credentials. Authentication failed." });
    } else {
      res.status(500).json({ message: "An error occurred while sending the email." });
    }
  }
};

export default handler;

then the function that calls the route =>

const onSubmit = async (data: FormData) => {
    const res = await fetch('/api/mail', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'accept': 'application/json , text/plain, */*'
      },
      body: JSON.stringify(data)

    })
    console.log(res, 'response from server')
    if (res.status === 200) {
      const json = await res.json()
      toast.success(json.message)
      reset()
      router.push('/')
    }
  }

But whenever i go to the api route like https://domain.com.ng/api/mail , i get an error occurred while sending the email

And if i fill in the form to send , i get internal server error
I expected it to log status ok and send the message.

So finally , i have been able to stop getting the internal server error as a result of using async await , but still yet , the recipient is not receiving the mail even though it returns success.

my server log

  • App 9469 output: at TLSSocket.SMTPConnection._onSocketError (/home2/funditco/nodevenv/frontend_test/16/lib/node_modules/nodemailer/lib/smtp-connection/index.js:194:45)
    App 9469 output: at SMTPConnection._onError (/home2/funditco/nodevenv/frontend_test/16/lib/node_modules/nodemailer/lib/smtp-connection/index.js:780:14)
    App 9469 output: at SMTPConnection. (/home2/funditco/nodevenv/frontend_test/16/lib/node_modules/nodemailer/lib/smtp-transport/index.js:176:24)
    App 9469 output: at /home2/funditco/nodevenv/frontend_test/16/lib/node_modules/nodemailer/lib/mailer/index.js:230:21

2

Answers


  1. Chosen as BEST ANSWER

    It is working now , so the reason i get internal server error was as a result of hostname , my hosting provider already set up the smtp configuration . All i did was change the hostname to 'localhost'


  2. Thanks.

    I have got same error but i see your anwer more detail.

    Just curious about that you replaced the ‘localhost’ for hostname.

    Can you explain about that?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search