Here’s my html form:
<form class="contact-form" action="/" method="POST">
<input type="text" id="name" name="name" placeholder="Name" required>
<input type="email" name="email" id="email" placeholder="Email" required>
<input type="text" name="subject" id="subject" placeholder="Subject" required>
<textarea type="textbox" name="message" id="message" placeholder="Your Message" required></textarea>
<button class="submit-button" type="submit">Send Message</button>
</form>
client side js:
const contactForm = document.querySelector(".contact-form");
const handleSubmit = (e) => {
e.preventDefault();
let formData = new FormData(contactForm);
let urlEncodedFormData = new URLSearchParams(formData);
fetch("/", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: urlEncodedFormData,
})
.then((response) => {
if (response.ok) {
alert('Email sent');
contactForm.reset();
} else {
throw new Error('Request failed with status: ' + response.status);
}
})
.catch((error) => {
alert('Something went wrong!')
console.error(error);
});
}
contactForm.addEventListener('submit', handleSubmit);
server side js:
const express = require('express');
const nodemailer = require('nodemailer')
const app = express();
const PORT = process.env.PORT || 5000;
// Middleware
app.use(express.static(__dirname + '/public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
// Add a route to handle /index.html specifically
app.get('/index.html', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/contact.html')
})
app.post('/', (req, res) => {
console.log(req.body);
const { name, email, subject, message } = req.body; // Destructure form fields for easier access
console.log('Name:', name);
console.log('Email:', email);
console.log('Subject:', subject);
console.log('Message:', message);
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: "ambrishabhijatya@gmail.com",
pass: 'gmail_app_pass' /*hidden*/
}
})
const mailOptions = {
from: email,
to: 'ambrishabhijatya@gmail.com',
subject: `${email}: ${subject}`,
text: `Message from ${name}: \n ${message}`
}
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
res.send('error')
} else {
console.log('Email Sent: ' + info.response);
res.send('success')
}
})
})
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
})