Icon
Get In Touch
#nextjs

Contact form with nodemailer

Install Dependencies with the following commands.

1
npm 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.

1
const handleSubmit = async (e: React.FormEvent) => {
2
e.preventDefault();
3
setIsLoading(true);
4
const res = await fetch("/api/contact", {
5
method: "POST",
6
headers: {
7
"Content-Type": "application/json",
8
},
9
body: JSON.stringify({ name, email, message }),
10
});
11
12
setIsLoading(false);
13
14
if (res.status === 200) {
15
alert("Message sent successfully.");
16
setName("");
17
setEmail("");
18
setMessage("");
19
} else {
20
alert("Uh oh! Something went wrong.");
21
}
22
};

Create an API route for handling the form submission. Make sure to update your field variables.

1
import { NextRequest, NextResponse } from "next/server";
2
import nodemailer from "nodemailer";
3
4
export async function POST(req: NextRequest) {
5
const { name, email, message } = await req.json();
6
7
if (!name || !email || !message) {
8
return NextResponse.json(
9
{ message: "All fields are required." },
10
{ status: 400 }
11
);
12
}
13
14
const transporter = nodemailer.createTransport({
15
service: "gmail",
16
auth: {
17
user: process.env.EMAIL_USER,
18
pass: process.env.EMAIL_PASS,
19
},
20
});
21
22
const mailOptions = {
23
from: email,
24
to: process.env.EMAIL_USER,
25
subject: 'New message from CODEBLOCKZ Website',
26
html: 'structure your message here',
27
};
28
29
try {
30
await transporter.sendMail(mailOptions);
31
return NextResponse.json(
32
{ message: "Message sent successfully!" },
33
{ status: 200 }
34
);
35
} catch (error) {
36
console.error(error);
37
return 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

1
EMAIL_USER=youremailaddress
2
EMAIL_PASS=yourappaddress

©2024 Codeblockz

Privacy Policy