-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
102 lines (95 loc) · 2.05 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
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
let express = require("express");
let nodemailer = require("nodemailer");
let bodyParser = require("body-parser");
let cors = require("cors");
const { check, validationResult } = require("express-validator/check");
const config = require("./config/config.js");
let lib = require("./bin/lib");
let app = express();
app.use(cors());
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
//Initialize the smtp transporter
let smtpTransport = nodemailer.createTransport({
host: config.mailserver.host,
port: config.mailserver.port,
secure: config.mailserver.secure,
auth: {
user: config.mailserver.user,
pass: config.mailserver.password
}
});
//Post route that takes in the info and sends the email
app.post(
"/",
[
//Validate the post data
check("email")
.not()
.isEmpty()
.isEmail(),
check("name")
.not()
.isEmpty()
.isString(),
check("message")
.not()
.isEmpty()
.isString(),
check("phone")
.not()
.isEmpty()
.isLength({
min: 10
})
],
function(req, res) {
//Return 422 status if there are validation errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({
errors: errors.array()
});
}
//Set up the parameters from the post data
let mailParameters = {
to: config.message.toAdress,
subject: config.message.subject,
from: config.message.fromAdress,
replyTo: req.body.email,
html: lib.getEmailContentFromDetails(
req.body.name,
req.body.email,
req.body.phone,
req.body.message
)
};
//Send the mail according set parameters
smtpTransport.sendMail(mailParameters, function(err, response) {
if (err) {
console.log(err);
res.status(500).json({
status: "error",
error: err
});
} else {
console.log("Message sent");
res.json({
status: "success"
});
}
});
}
);
//Starting webserver
app.listen(config.webServer.port, function(err) {
if (err) {
console.log(err);
} else {
console.log("Listening on port on " + config.webServer.port);
}
});