-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.js
66 lines (61 loc) · 1.77 KB
/
handler.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
const aws = require("aws-sdk");
const ses = new aws.SES();
const mainEmail = process.env.MAIN_EMAIL;
const secondaryEmail = process.env.SECONDARY_EMAIL;
const myDomain = process.env.DOMAIN;
function generateResponse(code, payload) {
return {
statusCode: code,
headers: {
"Access-Control-Allow-Origin": myDomain,
"Access-Control-Allow-Headers": "x-requested-with",
"Access-Control-Allow-Credentials": true
},
body: JSON.stringify(payload)
};
}
function generateError(code, err) {
console.log(err);
return {
statusCode: code,
headers: {
"Access-Control-Allow-Origin": myDomain,
"Access-Control-Allow-Headers": "x-requested-with",
"Access-Control-Allow-Credentials": true
},
body: JSON.stringify(err.message)
};
}
function generateEmailParams(body) {
const { email, name, subject, message } = JSON.parse(body);
console.log(email, name, subject, message);
if (!(email && name && subject && message)) {
throw new Error("Missing parameters! Make sure to add parameters \'email\', \'name\', \'subject\', \'message\'.");
}
return {
Source: secondaryEmail,
Destination: { ToAddresses: [mainEmail] },
ReplyToAddresses: [email],
Message: {
Body: {
Text: {
Charset: "UTF-8",
Data: `Message sent from email ${email} by ${name}\nSubject: ${subject}\nMessage: ${message}`
}
},
Subject: {
Charset: "UTF-8",
Data: `You received a message from ${myDomain}!`
}
}
};
}
module.exports.send = async (event) => {
try {
const emailParams = generateEmailParams(event.body);
const data = await ses.sendEmail(emailParams).promise();
return generateResponse(200, data);
} catch (err) {
return generateError(500, err);
}
};