import htmlToText from 'html-to-text'
import nodemailer from 'nodemailer'
import fs from 'fs'
import twig from 'twig'
export default class EmailService {
static init() {
if (this.isMocked()) {
console.warn('> EmailService: WARNING: EMAIL IS MOCKED!')
}
}
static getTransporter() {
if (process.env.SMTP_HOST == undefined || process.env.SMTP_PORT == undefined) {
throw new Error("Invalid SMTP config")
}
const config: any = {
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,
}
}
return nodemailer.createTransport(config)
}
// static getMailgunClient(): Mailgun {
// return new Mailgun({
// apiKey: '4e64a894f18cc2fe10e4e4829b0048f3-7caa9475-241eee2c'
// })
// }
static nativeSend(params: any): Promise {
// return this.getMailgunClient().sendMessage('sandboxeb2300b9439e4fe7bd2cca8f52ac7bd6.mailgun.org', {
// from: params.from,
// to: params.to,
// subject: params.subject,
// text: params.text,
// html: params.html
// })
return this.getTransporter().sendMail(params)
}
static send(to: string, subject: string, templateName: string, templateParams: any): Promise {
const viewPath: string = __dirname + '/../views/emails/'
const data: Buffer = fs.readFileSync(viewPath + templateName + '.twig')
const html: string = twig.twig({
// @ts-ignore
allowInlineIncludes: true,
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"
subject += " - Forum des associations 2020"
return new Promise((resolve, reject) => {
const config: any = {
from: '"Forum des associations - Espace Condorcet Centre Social" ',
to, subject, text, html
}
if (this.isMocked()) {
delete config.html
console.log(config)
resolve()
} else {
this.nativeSend(config).then(res => {
console.log('> A "' + templateName + '" email was sent')
resolve()
}).catch(err => {
console.log('> A "' + templateName + '" email failed to be sent')
console.error(err)
reject()
})
}
})
}
static getWebUiBaseUrl() {
return process.env.WEB_UI_URL === undefined ? "URL_NOT_FOUND" : process.env.WEB_UI_URL
}
static getBaseUrl() {
return process.env.BASE_URL === undefined ? "URL_NOT_FOUND" : process.env.BASE_URL
}
static isMocked() {
// WARNING ATTENTION REQUIRED
// CUSTOM DESACTIVATION PLEASE ENABLE IN PRODUCTION
return process.env.MOCK_EMAIL === "true"
}
}