I am trying to use NodeMailer with NextJS for my contact form. I created an endpoint Nodemailer API and tried to fetch POST to it. But I get a Server Internal 500 error.
Here is the API src/api/email/route.js
import { NextResponse } from 'next/server';
import nodemailer from 'nodemailer';
export async function POST(request) {
const { email, name, message } = await request.json();
const myEmail = process.env.MY_EMAIL;
const myPassword = process.env.MY_PASSWORD;
const transport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: myEmail,
pass: myPassword,
},
});
const mailOptions = {
from: myEmail,
to: myEmail,
// cc: email, (uncomment this line if you want to send a copy to the sender)
subject: `Message from ${name} (${email})`,
text: message,
};
const sendMailPromise = () =>
new Promise < string > ((resolve, reject) => {
transport.sendMail(mailOptions, function (err) {
if (!err) {
resolve('Email sent');
} else {
reject(err.message);
}
});
});
try {
await sendMailPromise();
return NextResponse.json({ message: 'Email sent' });
} catch (err) {
return NextResponse.json({ error: err }, { status: 500 });
}
}
And here is the contact page src/contact/page.js
'use client';
import { useForm } from 'react-hook-form';
import { sendEmail } from '@/utils/send-email';
const Contact = () => {
const { register, handleSubmit } = useForm();
function onSubmit(data) {
sendEmail(data);
}
return (
<form onSubmit={handleSubmit(onSubmit)} className="w-full max-w-lg mx-auto py-10">
...
</form>
);
};
export default Contact;
And here is the the function to send email src/utils/send-email.js
export function sendEmail(data) {
const apiEndpoint = '/api/email';
console.log(JSON.stringify(data))
fetch(apiEndpoint, {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((res) => res.json())
.then((response) => {
alert(response.message);
})
.catch((err) => {
alert(err);
});
}
When submitting the form, I receive a 500 error. I’ve double-checked my environment variables and they seem correct. Any insights on how to troubleshoot and resolve this issue would be greatly appreciated!