Ask Your Question
3

How can I transmit form data to an email in Next.js?

asked 2021-05-30 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-05-25 21:00:00 +0000

huitzilopochtli gravatar image

In Next.js, you can use a backend technology such as Node.js and its built-in nodemailer module to transmit form data to an email. Here's a basic example:

  1. In your Next.js component, create a form element with the necessary input fields and a submit button:
<form onSubmit={handleSubmit}>
  <label>
    Name:
    <input type="text" name="name" value={name} onChange={handleChange} />
  </label>
  <label>
    Email:
    <input type="email" name="email" value={email} onChange={handleChange} />
  </label>
  <label>
    Message:
    <textarea name="message" value={message} onChange={handleChange} />
  </label>
  <button type="submit">Send</button>
</form>
  1. In the handleSubmit function, use fetch to make a POST request to a server endpoint that will handle sending the email:
const handleSubmit = async (e) => {
  e.preventDefault();
  const res = await fetch('/api/send-email', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ name, email, message }),
  });
  // handle the response as needed
};
  1. Create a serverless API route in /pages/api/send-email.js that will receive the form data, configure and send the email using nodemailer:
import nodemailer from 'nodemailer';

export default async function handler(req, res) {
  const { name, email, message } = req.body;

  const transporter = nodemailer.createTransport({
    // configuration for the email service provider
  });

  const mailOptions = {
    from: email,
    to: 'your-email@example.com',
    subject: `${name} sent you a message from your website`,
    text: message,
  };

  try {
    await transporter.sendMail(mailOptions);
    res.status(200).json({ message: 'Email sent' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
}

Note: You will need to set up a valid email service provider account and configure the transporter object accordingly with the provider's SMTP settings.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-05-30 11:00:00 +0000

Seen: 12 times

Last updated: May 25 '22