From 2f36cea1b058796da180b821cd5670ba90dab741 Mon Sep 17 00:00:00 2001 From: cgeek Date: Sun, 20 Sep 2020 11:36:44 +0200 Subject: [PATCH] mailing: grouped emails --- app.yml | 2 +- src/lib/mail.ts | 44 ++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/app.yml b/app.yml index 4fd55f9..9da37b8 100644 --- a/app.yml +++ b/app.yml @@ -38,7 +38,7 @@ wwMeta: mail: enabled: false - frequency: 10000 # 10" + frequency: 3000 # 10" host: smtp.sparkpostmail.com port: 587 auth: LOGIN diff --git a/src/lib/mail.ts b/src/lib/mail.ts index d978439..739ba2b 100644 --- a/src/lib/mail.ts +++ b/src/lib/mail.ts @@ -4,7 +4,7 @@ import * as nodemailer from 'nodemailer' import * as os from 'os' const DEFAULT_FREQUENCY = 5 * 60 * 1000 // 5' -const queue: EmailContent[] = [] +const queue: MailContent[] = [] let conf: ConfMail|undefined export function initConfMail(confMail: ConfMail) { @@ -26,16 +26,52 @@ export async function queueEmail(subject: string, html: string, cc?: string) { console.log(`[mail] added 1 mail to queue`) } +function consumeMessages(cc: string): MailContent[] { + const mails: MailContent[] = [] + for (let i = 0; i < queue.length; i++) { + const mail = queue[i] + if (mail.cc === (cc || undefined)) { + mails.push(queue[i]) + queue.splice(i, 1) + i-- + } + } + return mails +} + async function consumeQueue() { console.log(`[mail] consuming mailing queue: ${queue.length} messages to be sent`) while (queue.length) { - const mail = queue.shift() - if (mail) { + if (queue.length > 1) { + const ccs = queue.reduce((ccs, mail) => { + const cc = getGroup(mail) + if (ccs.indexOf(cc) === -1) { + ccs.push(cc) + } + return ccs + }, [] as string[]) + console.log(`[mail] grouping messages into ${ccs.length} group(s)`) + for (const cc of ccs) { + const messages: MailContent[] = consumeMessages(cc) + const subject = `[dw] [${os.hostname}] ${messages.length} notifications` + let body = '' + for (const message of messages) { + body += `

${message.subject}

\n` + body += `
${message.body}
\n` + } + await sendEmail(subject, body, cc || undefined) + } + } else { + const mail = queue.shift() as MailContent await sendEmail(mail.subject, mail.body, mail.cc) } } } +function getGroup(mail: MailContent) { + return mail.cc || '' +} + async function sendEmail(subject: string, html: string, cc?: string) { if (!conf) { @@ -111,7 +147,7 @@ export const mail = { }, } -interface EmailContent { +interface MailContent { subject: string body: string cc?: string