Skip to content

Commit

Permalink
Merge pull request #60 from JumboCode/con-page-email-conn
Browse files Browse the repository at this point in the history
completed contact page translation and admin email connection
  • Loading branch information
myix765 authored Dec 7, 2024
2 parents e4f418e + 42fba83 commit 755d115
Show file tree
Hide file tree
Showing 5 changed files with 103 additions and 37 deletions.
46 changes: 41 additions & 5 deletions api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const cors = require('cors');
const mongo = require('mongodb');
const mongoose = require('mongoose');
const mongoSanitize = require('express-mongo-sanitize');
const nodemailer = require('nodemailer');

const app = express()
app.use(cors())
Expand Down Expand Up @@ -216,21 +217,56 @@ app.get('/api/users', async (req, res) => {
// Post Contact
app.post('/api/contact', async (req, res) => {
const { name, email, subject, message } = req.body

try {
const newContact = new Contact({
name,
email,
subject,
message
})
await newContact.save()
});
await newContact.save();

// Nodemailer setup
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.ADMIN_EMAIL,
pass: process.env.ADMIN_PASSWORD,
},
});

transporter.verify((error, success) => {
if (error) {
console.error('Error initializing transporter:', error);
} else {
console.log('Transporter is ready to send emails', success);
}
});


const mailOptions = {
from: email,
to: process.env.ADMIN_EMAIL,
subject: `Contact Form: ${subject}`,
html: `
<p><strong>From:</strong> ${name} (${email})</p>
<p><strong>Subject:</strong> ${subject}</p>
<p><strong>Message:</strong></p>
<p>${message}</p>
`
};

res.status(201).json({ message: 'Inquiry submitted successfully' })
// Send email
await transporter.sendMail(mailOptions);

res.status(201).json({ message: 'Inquiry and email submitted successfully' });
}
catch (err) {
res.status(500).json({ message: 'Error submitting inquiry' });
console.error('Error submitting inquiry:', err);
res.status(500).json({ message: 'Error submitting inquiry', error: err.message });
}
})
});


/* CLASS RELATED ENDPOINTS */
Expand Down
34 changes: 24 additions & 10 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"i18next": "^23.16.4",
"i18next-browser-languagedetector": "^8.0.0",
"i18next-http-backend": "^2.6.2",
"nodemailer": "^6.9.16",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-i18next": "^15.1.0",
Expand Down
16 changes: 12 additions & 4 deletions src/api/contact-wrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,22 @@ const postContact = async (body) => {
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body)
})
body: JSON.stringify(body),
});

return response
if (!response.ok) {
const errorResponse = await response.json();
console.error('Error response from /api/contact:', errorResponse);
throw new Error(errorResponse.message || 'Failed to submit contact form');
}

return response;
} catch (error) {
console.error('Contact endpoint post error:', error);
throw error; // Propagate the error to the caller
}
}
};


export {
postContact
Expand Down
43 changes: 25 additions & 18 deletions src/pages/Contact.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import { postContact } from '@/api/contact-wrapper';
import Form from "@/components/Form/Form"
import FormInput from '@/components/Form/FormInput';
import FormSubmit from '@/components/Form/FormSubmit';
import { useTranslation } from 'react-i18next';

export default function Contact() {
const { t } = useTranslation();

const [formData, setFormData] = useState({
name: '',
Expand All @@ -20,29 +22,34 @@ export default function Contact() {

const handleSubmit = async (e) => {
e.preventDefault();
const contactData = {
name: e.target.name.value,
email: e.target.email.value,
subject: e.target.subject.value,
message: e.target.message.value
};
try {
const response = await postContact(formData)
const response = await postContact(contactData);

if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
if (response.ok) {
alert("Message submitted successfully!");
} else {
const errorResponse = await response.json();
alert(`Failed to send message: ${errorResponse.message}`);
}
const json = await response.json()
console.log(json)
alert("Inquiry submitted successfully!")

} catch (err) {
console.error(error.message)
alert("There was an error submitting the inquiry.")
console.error('Error in handleSubmit:', err);
alert("There was an error submitting the inquiry.");
}
};


return (
<div className="w-full h-full bg-white flex flex-col sm:flex-row justify-center items-center">
<div className="sm:w-1/3 w-full p-8">
<h2 className="text-3xl font-semibold mb-6">CONTACT US</h2>
<h2 className="text-3xl font-semibold mb-6">{t("contact_heading")}</h2>
<p className="mb-2 text-lg">
Email:
{t("email_field")}:
<a href="mailto:[email protected]" className="text-black">
[email protected]
</a>
Expand All @@ -58,9 +65,9 @@ export default function Contact() {
<div className="sm:w-2/3 w-full bg-blue-200 p-10 flex justify-center">
{/* form box */}
<Form width="w-3/5">
<h2 className="text-2xl font-semibold mb-2">Get in Touch</h2>
<h2 className="text-2xl font-semibold mb-2">{t("form_heading")}</h2>
<p className="mb-4 text-gray-600 opacity-70">
Let us know if you have questions or concerns.
{t("form_description")}
</p>
<form
onSubmit={handleSubmit}
Expand All @@ -69,36 +76,36 @@ export default function Contact() {
<FormInput
type="text"
name="name"
placeholder="Name"
placeholder={t("name_field")}
value={formData.name}
onChange={handleChange}
isRequired={true}
/>
<FormInput
type="email"
name="email"
placeholder="Email"
placeholder={t("email_field")}
value={formData.email}
onChange={handleChange}
isRequired={true}
/>
<FormInput
type="text"
name="subject"
placeholder="Subject"
placeholder={t("subject_field")}
value={formData.subject}
onChange={handleChange}
isRequired={true}
/>
<FormInput
type="textarea"
name="message"
placeholder="Message"
placeholder={t("message_field")}
value={formData.message}
onChange={handleChange}
required
/>
<FormSubmit label={"Submit"} />
<FormSubmit label={t("submit_button")} />
</form>
</Form>
</div>
Expand Down

0 comments on commit 755d115

Please sign in to comment.