server/src/EmailService.ts

49 lines
1.6 KiB
TypeScript
Raw Normal View History

2020-07-11 22:42:00 +00:00
import htmlToText from 'html-to-text'
2020-07-10 20:44:01 +00:00
import nodemailer from 'nodemailer'
2020-07-12 10:30:55 +00:00
import fs from 'fs'
import twig from 'twig'
2020-07-10 20:44:01 +00:00
export default class EmailService {
static getTransporter() {
if (process.env.SMTP_HOST == undefined || process.env.SMTP_PORT == undefined) {
throw new Error("Invalid SMTP config")
}
2020-07-12 10:30:55 +00:00
const config: any = {
2020-07-10 20:44:01 +00:00
host: process.env.SMTP_HOST,
port: parseInt(process.env.SMTP_PORT),
secure: process.env.SMTP_SECURE == 'true',
auth: {
user: process.env.SMTP_USERNAME,
pass: process.env.SMTP_PASSWORD,
}
2020-07-12 10:30:55 +00:00
}
console.log(config)
return nodemailer.createTransport(config)
2020-07-10 20:44:01 +00:00
}
2020-07-11 22:42:00 +00:00
2020-07-12 10:30:55 +00:00
static send(to: string, subject: string, templateName: string, templateParams: any): Promise<any> {
const viewPath: string = __dirname + '/../views/emails/'
const data: Buffer = fs.readFileSync(viewPath + templateName + '.twig')
const html: string = twig.twig({ data: data.toString() }).render(templateParams)
const text: string = htmlToText.fromString(html, { wordwrap: 130 })
// for now replace every email by a predefined one
console.info(to + ' replaced')
to = "spamfree@matthieubessat.fr"
return new Promise((resolve, reject) => {
const config: any = {
from: '"Forum des associations - Espace Condorcet Centre Social" <ne-pas-repondre@espacecondorcet.org>',
to, subject, text, html
}
console.log(config.html)
this.getTransporter().sendMail(config).then(info => {
console.log(info)
resolve()
}).catch(err => {
console.log(err)
reject()
})
2020-07-11 22:42:00 +00:00
})
}
2020-07-10 20:44:01 +00:00
}