This commit is contained in:
root 2020-07-12 10:30:55 +00:00
parent bc70ca4e05
commit 0f50ac2947
5 changed files with 82 additions and 33 deletions

View file

@ -1,13 +1,14 @@
import htmlToText from 'html-to-text' import htmlToText from 'html-to-text'
import nodemailer from 'nodemailer' import nodemailer from 'nodemailer'
import { resolveContent } from 'nodemailer/lib/shared' import fs from 'fs'
import twig from 'twig'
export default class EmailService { export default class EmailService {
static getTransporter() { static getTransporter() {
if (process.env.SMTP_HOST == undefined || process.env.SMTP_PORT == undefined) { if (process.env.SMTP_HOST == undefined || process.env.SMTP_PORT == undefined) {
throw new Error("Invalid SMTP config") throw new Error("Invalid SMTP config")
} }
return nodemailer.createTransport({ const config: any = {
host: process.env.SMTP_HOST, host: process.env.SMTP_HOST,
port: parseInt(process.env.SMTP_PORT), port: parseInt(process.env.SMTP_PORT),
secure: process.env.SMTP_SECURE == 'true', secure: process.env.SMTP_SECURE == 'true',
@ -15,27 +16,34 @@ export default class EmailService {
user: process.env.SMTP_USERNAME, user: process.env.SMTP_USERNAME,
pass: process.env.SMTP_PASSWORD, pass: process.env.SMTP_PASSWORD,
} }
}) }
console.log(config)
return nodemailer.createTransport(config)
} }
static send(to: string, subject: string, html: string) { static send(to: string, subject: string, templateName: string, templateParams: any): Promise<any> {
return new Promise(resolve => { const viewPath: string = __dirname + '/../views/emails/'
console.log('to', to) const data: Buffer = fs.readFileSync(viewPath + templateName + '.twig')
console.log('subject', subject) const html: string = twig.twig({ data: data.toString() }).render(templateParams)
console.log('html', html) const text: string = htmlToText.fromString(html, { wordwrap: 130 })
// this.getTransporter().sendMail({
// from: '"Forum des associations - Espace Condorcet Centre Social" <ne-pas-repondre@espacecondorcet.org>', // for now replace every email by a predefined one
// to, console.info(to + ' replaced')
// subject, to = "spamfree@matthieubessat.fr"
// text: htmlToText.fromString(html, { wordwrap: 130 }),
// html, return new Promise((resolve, reject) => {
// }).then(info => { const config: any = {
// console.log("Message sent: %s", info.messageId); from: '"Forum des associations - Espace Condorcet Centre Social" <ne-pas-repondre@espacecondorcet.org>',
// console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info)); to, subject, text, html
// resolve(info) }
// }).catch(err => { console.log(config.html)
// console.error(err) this.getTransporter().sendMail(config).then(info => {
// }) console.log(info)
resolve()
}).catch(err => {
console.log(err)
reject()
})
}) })
} }
} }

View file

@ -12,9 +12,6 @@ import AdminAuthMiddleware from './middlewares/AdminAuthMiddleware'
import DelegateAuthMiddleware from './middlewares/DelegateAuthMiddleware' import DelegateAuthMiddleware from './middlewares/DelegateAuthMiddleware'
import PublicController from './controllers/PublicController' import PublicController from './controllers/PublicController'
import cors from 'cors' import cors from 'cors'
import twig from 'twig'
console.log('WOOWOWO')
dotenv.config({ dotenv.config({
path: __dirname + '/../.env' path: __dirname + '/../.env'

View file

@ -77,24 +77,23 @@ export default class AdminOrganizationController {
} }
static sendEmailToken(req: express.Request, res: express.Response) { static sendEmailToken(req: express.Request, res: express.Response) {
const path: string = __dirname + '/../../views/email/token.twig'
Organization.findById(req.params.id).then(data => { Organization.findById(req.params.id).then(data => {
if (data === null) { if (data === null) {
return res.status(404).json({ success: false, errors: [ { code: 'not-found', message: 'Organization not found' } ] }) return res.status(404).json({ success: false, errors: [ { code: 'not-found', message: 'Organization not found' } ] })
} }
Twig.renderFile(path, { filename: '', settings: { foo: 'bar' } }, (err: any, html: any) => { EmailService.send(
console.log(html) data.get('email'),
console.log(err) "Votre lien secret pour modifier votre association - Forum des associations 2020",
EmailService.send( "token",
data.get('email'), { organizationName: data.get('adminName'), token: data.get('token') }
"Votre lien secret pour modifier votre association - Forum des associations 2020", ).then(() => {
html console.log('email sent')
)
}) })
res.json({ success: true }) res.json({ success: true })
}) })
} }
static resetToken(req: express.Request, res: express.Response) { static resetToken(req: express.Request, res: express.Response) {
Organization.updateOne({ _id: req.params.id }, { Organization.updateOne({ _id: req.params.id }, {
token: cryptoRandomString({ length: 10, type: 'distinguishable' }), token: cryptoRandomString({ length: 10, type: 'distinguishable' }),

40
test_mail.js Normal file
View file

@ -0,0 +1,40 @@
"use strict";
const nodemailer = require("nodemailer");
// async..await is not allowed in global scope, must use a wrapper
async function main() {
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
//let testAccount = await nodemailer.createTestAccount();
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: 'smtp.mailgun.org',
port: 587,
secure: false,
auth: {
user: 'hello@sandboxeb2300b9439e4fe7bd2cca8f52ac7bd6.mailgun.org',
pass: 'b69383e5abcfc41014549be7d6b798bc-87c34c41-c9e7e87c'
}
});
// send mail with defined transport object
let info = await transporter.sendMail({
from: '"Forum des associations - Espace Condorcet Centre Social" <ne-pas-repondre@espacecondorcet.org>',
to: 'spamfree@matthieubessat.fr',
subject: 'Votre lien secret pour modifier votre association - Forum des associations 2020',
text: `Bonjour gérant de l'association nommée "We Robot's" Voici votre clée: P0118KUHD8`,
html: `Bonjour gérant de l'association nommée "We Robot's" \n` +
'\n' +
'Voici votre clée: P0118KUHD8\n'
});
console.log("Message sent: %s", info.messageId);
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>
// Preview only available when sending through an Ethereal account
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}
main().catch(console.error);

View file

@ -0,0 +1,5 @@
Bonjour gérant de l'association nommée "{{ organizationName }}"
Voici votre clée: {{ token }}
Coordialement