58 lines
2.3 KiB
JavaScript
58 lines
2.3 KiB
JavaScript
// contactController.js
|
|
module.exports = (pool, transporter) => {
|
|
|
|
// The main function that handles the form submission
|
|
const submitForm = async (req, res) => {
|
|
const { firstName, lastName, organization, email, phone, contactMethod, message } = req.body;
|
|
|
|
try {
|
|
// 1. Save submission to the database
|
|
const result = await pool.query(
|
|
`INSERT INTO submissions(first_name, last_name, organization, email, phone, contact_method, message)
|
|
VALUES($1, $2, $3, $4, $5, $6, $7) RETURNING *`,
|
|
[firstName, lastName, organization, email, phone, contactMethod, message]
|
|
);
|
|
|
|
console.log('Successfully saved submission to the database:', result.rows[0]);
|
|
|
|
// 2. Send the email notification
|
|
const mailOptions = {
|
|
from: `"Contact Form" <contact@dlseitz.dev>`,
|
|
to: process.env.EMAIL_RCPT,
|
|
subject: 'New Contact Form Submission',
|
|
html: `
|
|
<h3>New Submission</h3>
|
|
<ul>
|
|
<li><strong>First Name:</strong> ${firstName}</li>
|
|
<li><strong>Last Name:</strong> ${lastName}</li>
|
|
<li><strong>Organization:</strong> ${organization}</li>
|
|
<li><strong>Email:</strong> ${email}</li>
|
|
<li><strong>Phone:</strong> ${phone}</li>
|
|
<li><strong>Contact Method:</strong> ${contactMethod}</li>
|
|
</ul>
|
|
<p><strong>Message:</strong></p>
|
|
<p>${message}</p>
|
|
`,
|
|
};
|
|
|
|
const emailInfo = await transporter.sendMail(mailOptions);
|
|
console.log('Message sent: %s', emailInfo.messageId);
|
|
|
|
res.status(200).json({
|
|
message: 'Form submitted successfully and saved to the database!',
|
|
dataReceived: req.body
|
|
});
|
|
|
|
} catch (err) {
|
|
console.error('An error occurred during form submission:', err.stack);
|
|
res.status(500).json({
|
|
message: 'An error occurred. Please try again.',
|
|
error: err.message
|
|
});
|
|
}
|
|
};
|
|
|
|
return {
|
|
submitForm,
|
|
};
|
|
}; |