-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
89 lines (78 loc) · 2.23 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
86
87
88
89
require('dotenv').config();
const fs = require('fs');
const express = require('express');
const multer = require('multer');
const transporter = require('./createTransporter');
const app = express();
app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, `${file.fieldname}_${Date.now()}_${file.originalname}`);
},
});
const attachmentUpload = multer({
storage,
}).single('attachment');
app.get('/', (req, res) => {
res.sendFile(`${__dirname}/public/index.html`);
});
app.get('/success', (req, res) => {
res.sendFile(`${__dirname}/public/success.html`);
});
app.post('/sendEmail', (req, res) => {
attachmentUpload(req, res, async (error) => {
if (error) {
console.log(error);
return res.send('Error uploading file');
} else {
const recipient = req.body.email;
const subject = req.body.subject;
const message = req.body.message;
const attachmentPath = req.file.path;
// e-mail option
let mailOptions = {
from: process.env.SENDER_EMAIL,
to: recipient,
subject,
text: message,
attachments: [
{
path: attachmentPath,
},
],
};
try {
// Method to send e-mail out
let emailTransporter = await transporter();
emailTransporter.sendMail(mailOptions, function (error, info) {
if (error) {
// failed block
console.log(error);
} else {
// Success block
console.log(`Email sent: ${info.response}`);
fs.unlink(attachmentPath, (err) => {
if (err) {
res.end(err);
} else {
console.log(`${attachmentPath} has been deleted`);
return res.redirect('/success');
}
});
}
});
} catch (err) {
return console.log(error);
}
}
});
});
const PORT = process.env.PORT;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});