-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (76 loc) · 2.45 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { config } from "./config.js";
import { Folders } from "./src/folders.js";
import { Parser } from "./src/parser.js";
import { Subscriptions } from "./src/subscriptions.js";
import { getSmtpAccount } from "./src/smtp.js";
import nodemailer from "nodemailer";
const cfg = config;
// Test should be true even if testing.enabled is set to false if the command line argument "test" is provided.
if (process.argv.length > 3) {
throw new Error("Only one command line argument is allowed.");
}
if (process.argv[2] === "test") {
cfg.testing.enabled = true;
}
/**
* Creates a transport agent with the given configuration.
*
* @param {{host:string, port: number, auth: {user: string, pass:string},
* security: string }} config to be used to create the transporter.
* @returns Object the transporter agent.
*/
function getTransporter(config = cfg.smtp) {
const transporter = nodemailer.createTransport(config);
return transporter;
}
/**
* Sends a message by email using the given transport agent.
*
* If no transport agent is provided, creates a default transfort agent using
* the global config file.
*
* @param {Object} message to be sent.
* @param {Object} transport agent to be used to send the email.
*/
async function sendMail(message, transport = null) {
const smtpAccount = await getSmtpAccount();
if (!transport) {
transport = getTransporter(smtpAccount);
}
try {
await transport.sendMail(message, handleMailSent);
} catch (e) {
console.log('Error sending email:', message, e.code, e.message);
}
}
function handleMailSent(err, info) {
if (err) console.error("Error sending email:", err);
else console.log("Successfully sent mail:", info);
}
async function sendEmailAlerts() {
const folders = Folders.findFolders();
for (let folder of folders) {
console.assert(["within", "past"].includes(folder.type));
const days = folder.type === "past" ? folder.days * -1 : folder.days;
try {
const subscriptions = await Subscriptions.getSubscriptions(
days,
folder.status
);
const messages = subscriptions
.filter(i => !!i)
.map((subscription) =>
Parser.folder2message(folder, subscription)
);
messages.forEach((m) => sendMail(m));
} catch (e) {
console.log('Could not process folder ', folder, 'due to', e.code, e.message);
}
}
}
sendEmailAlerts().then(() => console.log("done."));
export const app = {
getTransporter,
sendMail,
sendEmailAlerts
}