Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
147 lines (126 loc) · 4.04 KB
/
Copy pathserver.js
File metadata and controls
147 lines (126 loc) · 4.04 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
const express = require("express");
const cors = require("cors");
const path = require("path");
const config = require("./core/config");
const logger = require("./core/logger");
const verifyApiKey = require("./core/auth");
const { sendMail, verifyTransporter } = require("./core/mailer");
const { router: serverInformation, endpointHitCounts } = require("./core/serverInformation");
const app = express();
// Middlewares
app.use(cors());
app.use(express.json({ limit: "10mb" }));
app.use(express.urlencoded({ extended: true }));
// Serve static assets from public folder
app.use(express.static(path.join(__dirname, "public")));
// Request logging
app.use((req, res, next) => {
logger.info(`${req.method} ${req.url}`);
next();
});
// Root: Serve MailSync documentation & interactive web UI
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "pages", "index.html"));
});
// Health check endpoint
app.get(["/health", "/api/health"], (req, res) => {
res.status(200).json({
status: "ok",
service: "MailSync",
timestamp: new Date().toISOString(),
});
});
// Server Information & Hit stats
app.use(["/server-info", "/api/info"], serverInformation);
// Recipient addresses are personal data: keep only the first character in logs.
const maskEmail = (address) => String(address).replace(/^(.).*(@.*)$/, "$1***$2");
// Diagnostic logs endpoint (requires the access key when one is configured)
app.get(["/logs", "/api/logs"], verifyApiKey, (req, res) => {
res.status(200).json({ logs: logger.getRecentLogs() });
});
// SMTP Connection Verification endpoint
app.get("/api/verify", async (req, res) => {
try {
await verifyTransporter();
res.status(200).json({
success: true,
message: "Transporter verified successfully. Ready to send emails.",
});
} catch (error) {
logger.error(`Transporter verification failed: ${error.message}`);
res.status(500).json({
success: false,
error: "Transporter verification failed",
details: error.message,
});
}
});
// Core Email Sending Endpoint: POST /mail & POST /api/mail
const handleSendMail = async (req, res) => {
const { email, to, name, fromName, from, subject, message, html } = req.body;
const recipient = email || to;
if (!recipient) {
return res.status(400).json({
success: false,
error: "Missing required field: 'email' (or 'to') is required.",
});
}
if (!message && !html) {
return res.status(400).json({
success: false,
error: "Missing required field: either 'message' or 'html' is required.",
});
}
// Basic email format validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(recipient)) {
return res.status(400).json({
success: false,
error: `Invalid email address format: '${recipient}'.`,
});
}
try {
const info = await sendMail({
email: recipient,
name,
fromName,
from,
subject,
message,
html,
});
endpointHitCounts.mail++;
logger.info(`Email successfully sent to ${maskEmail(recipient)} (Message ID: ${info.messageId})`);
res.status(200).json({
success: true,
message: "Email sent successfully",
messageId: info.messageId,
recipient,
});
} catch (error) {
logger.error(`Error sending email to ${maskEmail(recipient)}: ${error.message}`);
res.status(500).json({
success: false,
error: "Failed to send email",
details: error.message,
});
}
};
app.post("/mail", verifyApiKey, handleSendMail);
app.post("/api/mail", verifyApiKey, handleSendMail);
// 404 handler for unknown routes
app.use((req, res) => {
res.status(404).json({
success: false,
error: "Endpoint not found",
message: "Use POST /mail to send emails. Visit GET / for API documentation.",
});
});
// Start local server if run directly
if (require.main === module) {
app.listen(config.port, () => {
logger.info(`MailSync server running on port ${config.port}`);
console.log(`MailSync server active: http://localhost:${config.port}`);
});
}
module.exports = app;