-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemail.js
59 lines (53 loc) · 2.44 KB
/
email.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
const { cleanHTML, isValidEmail, isValidString } = require("../helpers/parseInput")
const { sgSendEmail } = require("../services/sendGrid")
const { pmSendEmail } = require("../services/postMark")
const { logEmail, logStatus } = require("./datastore")
/**
* Ensures that the required parameters are valid and cleans the HTML body
* @param { {} } params The parameters received
* @param { Boolean } enableHtmlEmail Whether HTML emails are enabled
* @param { [] } allowedHtmlTags If HTML emails is enabled, then the HTML tags that are allowed
* @returns { {} } A dictionary of the cleaned parameters. On error, returns an error object with the reason
*/
exports.precheckParams = (params, enableHtmlEmail=false, allowedHtmlTags=[]) => {
let requiredParams = {
to: params.to,
to_name: params.to_name,
from: params.from,
from_name: params.from_name,
subject: params.subject,
body: params.body
}
// Ensure we have the required parameters and they are all strings
let missingParams = Object.keys(requiredParams).filter((key) => {
if (!requiredParams[key] || !isValidString(requiredParams[key])) return key
})
if (missingParams.length > 0) {
throw Error(`Missing required parameters: ${missingParams.join(", ")}. They must be strings.`)
}
// Ensure the email addresses are valid
if (requiredParams.to && !isValidEmail(requiredParams.to) || requiredParams.from && !isValidEmail(requiredParams.from)) {
throw Error(`An email address is invalid. Emails addresses given: ${requiredParams.to}, ${requiredParams.from}`)
}
let cleanBody = cleanHTML(requiredParams.body, allowedHtmlTags)
return { ...requiredParams, body: cleanBody, isHTML: enableHtmlEmail }
}
/**
* Sends email via Sendgrid and if that fails, retries to send via Postmark
* @param { {} } params The parsed and clean parameters
*/
exports.sendEmail = async (params) => {
let service = "SendGrid"
try {
await sgSendEmail({ ...params })
logStatus({ message: "Successfully sent email via Sendgrid" })
} catch (e) {
let message = `Error sending with Sendgrid: ${e.message}`
await pmSendEmail({ ...params }).catch(e => {
throw Error(`${message}, unable to send via Postmark: ${e.message}`)
})
logStatus({ message: `${message}. Sent via PostMark instead!`})
service = "PostMark"
}
logEmail({ params, meta: { service, sent: Date.now() } })
}