1 | initial version |
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:
<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>
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
};
/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.