-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
65 lines (57 loc) · 1.41 KB
/
index.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
const { createTransport } = require('nodemailer');
const { SMTP_HOST, SMTP_USER, SMTP_PASSWORD } = process.env;
const SMTP_PORT = 587;
const transporter = createTransport({
host: SMTP_HOST,
port: SMTP_PORT,
auth: {
user: SMTP_USER,
pass: SMTP_PASSWORD,
},
tls: {
rejectUnauthorized: false,
},
});
/**
* Sends an email using the fields provided in the `event` parameter
*
* @param {{ from, to, subject, text, html }} event - All fields are mandatory
* @returns {{ statusCode, body }}
* @throws {Error} if a required field is missing
*/
const handler = async event => {
const { from, to, subject, text, html } = event;
const args = { from, to, subject, text, html };
try {
validateArgs(args);
const response = await sendMail(args);
console.info({ args, response });
return {
statusCode: 200,
body: JSON.stringify(response),
};
} catch (error) {
console.error({ error });
return {
statusCode: 500,
body: JSON.stringify({ error: error.message }),
};
}
};
const validateArgs = args => {
const requiredArgs = ['from', 'to', 'subject', 'text', 'html'];
requiredArgs.forEach(argName => {
if (!args[argName]) {
throw new Error(`'${argName}' is required`);
}
});
};
const sendMail = ({ from, to, subject, text, html }) =>
transporter.sendMail({
from,
to,
subject,
text,
html,
});
exports.handler = handler;