#nextjs
Contact form with nodemailer
Install Dependencies with the following commands.
1npm install nodemailer @types/nodemailer
use the following code snippit for your handlesubmit on your contact form. Make sure to match your fields, usestates and that the api point is set to the correct path.
1const handleSubmit = async (e: React.FormEvent) => {2e.preventDefault();3setIsLoading(true);4const res = await fetch("/api/contact", {5method: "POST",6headers: {7"Content-Type": "application/json",8},9body: JSON.stringify({ name, email, message }),10});1112setIsLoading(false);1314if (res.status === 200) {15alert("Message sent successfully.");16setName("");17setEmail("");18setMessage("");19} else {20alert("Uh oh! Something went wrong.");21}22};
Create an API route for handling the form submission. Make sure to update your field variables.
1import { NextRequest, NextResponse } from "next/server";2import nodemailer from "nodemailer";34export async function POST(req: NextRequest) {5const { name, email, message } = await req.json();67if (!name || !email || !message) {8return NextResponse.json(9{ message: "All fields are required." },10{ status: 400 }11);12}1314const transporter = nodemailer.createTransport({15service: "gmail",16auth: {17user: process.env.EMAIL_USER,18pass: process.env.EMAIL_PASS,19},20});2122const mailOptions = {23from: email,24to: process.env.EMAIL_USER,25subject: 'New message from CODEBLOCKZ Website',26html: 'structure your message here',27};2829try {30await transporter.sendMail(mailOptions);31return NextResponse.json(32{ message: "Message sent successfully!" },33{ status: 200 }34);35} catch (error) {36console.error(error);37return NextResponse.json(38{ message: "Failed to send message." },39{ status: 500 }40);41}42}
Create .env.local file in you root folder and store your gmail credentials. You will need to use an app password that you have to obtain in your gmail account
1EMAIL_USER=youremailaddress2EMAIL_PASS=yourappaddress
©2024 Codeblockz
Privacy Policy