-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
85 lines (74 loc) · 2.34 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import http from "http";
import nodemailer from "nodemailer";
import dotenv from "dotenv";
dotenv.config();
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: process.env.user,
pass: process.env.pass,
},
});
// HTTP server with CORS support
const server = http.createServer((req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
// Handle preflight request (OPTIONS)
if (req.method === "OPTIONS") {
res.statusCode = 204; // No content
res.end();
return;
}
if (req.method === "POST" && req.url === "/send-email") {
let body = "";
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", () => {
try {
const formData = JSON.parse(body);
if (!formData.name || !formData.email || !formData.message) {
res.statusCode = 400;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ message: "Missing required fields" }));
return;
}
const mailOptions = {
from: formData.email,
to: process.env.user,
subject: "Contact Form Submission",
text: `You have a new message from ${formData.name} (${formData.email}):\n\n${formData.message}`,
};
// Send the email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error("Error sending email:", error);
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ message: "Error sending email" }));
} else {
console.log("Email sent: " + info.response);
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ message: "Email sent successfully" }));
}
});
} catch (error) {
console.error("Error parsing JSON:", error);
res.statusCode = 400;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ message: "Invalid JSON in request body" }));
}
});
} else {
res.statusCode = 404;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ message: "Not Found" }));
}
});
// Start the server
const PORT = process.env.PORT || 3001;
server.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});