-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
76 lines (66 loc) · 2.13 KB
/
app.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
require('dotenv').config();
require('newrelic');
const express = require('express');
const nodemailer = require('nodemailer');
const ejs = require('ejs');
const path = require('path');
const helmet = require('helmet');
const { body, validationResult } = require('express-validator');
const logger = require('./logger');
const config = require('./config/config.js');
const app = express();
const PORT = config.app.port;
app.use(express.json());
app.use(express.urlencoded({ extended: true })); // For parsing application/x-www-form-urlencoded
app.use(helmet()); // Use Helmet for security
app.use(helmet.hidePoweredBy()); // Hide the X-Powered-By header
// Create an SMTP transporter
const smtpTransport = nodemailer.createTransport({
service: config.smtp.service,
auth: {
user: config.smtp.user,
pass: config.smtp.pass
}
});
// Set up EJS as the template engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Serve a form page
app.get('/', (req, res) => {
res.render('form'); // Renders the EJS form template
});
// Define a route for sending emails
app.post('/send', [
body('to').isEmail().withMessage('Invalid email address'),
body('subject').notEmpty().withMessage('Subject is required'),
body('text').notEmpty().withMessage('Text is required')
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { to, subject, text } = req.body;
const mailOptions = {
from: config.smtp.user,
to,
subject,
text
};
try {
await smtpTransport.sendMail(mailOptions);
res.status(200).send('Email sent successfully');
} catch (error) {
logger.error(`Error sending email: ${error.message}`);
res.status(500).send('Error sending email');
}
});
// Error handling middleware
app.use((err, req, res, next) => {
logger.error(`Unhandled error: ${err.message}`);
logger.error(err.stack); // Log stack trace for debugging
res.status(500).send('Something went wrong');
});
// Start the server
app.listen(PORT, () => {
logger.info(`Server is running on http://localhost:${PORT}`);
});