From 0f50ac2947cf03fb5bc3c2fad4171e237348b983 Mon Sep 17 00:00:00 2001 From: root Date: Sun, 12 Jul 2020 10:30:55 +0000 Subject: [PATCH] update --- src/EmailService.ts | 50 +++++++++++-------- src/app.ts | 3 -- .../AdminOrganizationController.ts | 17 +++---- test_mail.js | 40 +++++++++++++++ views/emails/token.twig | 5 ++ 5 files changed, 82 insertions(+), 33 deletions(-) create mode 100644 test_mail.js diff --git a/src/EmailService.ts b/src/EmailService.ts index e608492..f4d0933 100644 --- a/src/EmailService.ts +++ b/src/EmailService.ts @@ -1,13 +1,14 @@ import htmlToText from 'html-to-text' import nodemailer from 'nodemailer' -import { resolveContent } from 'nodemailer/lib/shared' +import fs from 'fs' +import twig from 'twig' export default class EmailService { static getTransporter() { if (process.env.SMTP_HOST == undefined || process.env.SMTP_PORT == undefined) { throw new Error("Invalid SMTP config") } - return nodemailer.createTransport({ + const config: any = { host: process.env.SMTP_HOST, port: parseInt(process.env.SMTP_PORT), secure: process.env.SMTP_SECURE == 'true', @@ -15,27 +16,34 @@ export default class EmailService { user: process.env.SMTP_USERNAME, pass: process.env.SMTP_PASSWORD, } - }) + } + console.log(config) + return nodemailer.createTransport(config) } - static send(to: string, subject: string, html: string) { - return new Promise(resolve => { - console.log('to', to) - console.log('subject', subject) - console.log('html', html) - // this.getTransporter().sendMail({ - // from: '"Forum des associations - Espace Condorcet Centre Social" ', - // to, - // subject, - // text: htmlToText.fromString(html, { wordwrap: 130 }), - // html, - // }).then(info => { - // console.log("Message sent: %s", info.messageId); - // console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info)); - // resolve(info) - // }).catch(err => { - // console.error(err) - // }) + 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({ 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" ', + to, subject, text, html + } + console.log(config.html) + this.getTransporter().sendMail(config).then(info => { + console.log(info) + resolve() + }).catch(err => { + console.log(err) + reject() + }) }) } } \ No newline at end of file diff --git a/src/app.ts b/src/app.ts index 1c8d4c5..129ba04 100644 --- a/src/app.ts +++ b/src/app.ts @@ -12,9 +12,6 @@ import AdminAuthMiddleware from './middlewares/AdminAuthMiddleware' import DelegateAuthMiddleware from './middlewares/DelegateAuthMiddleware' import PublicController from './controllers/PublicController' import cors from 'cors' -import twig from 'twig' - -console.log('WOOWOWO') dotenv.config({ path: __dirname + '/../.env' diff --git a/src/controllers/AdminOrganizationController.ts b/src/controllers/AdminOrganizationController.ts index 39aadee..13c83bc 100644 --- a/src/controllers/AdminOrganizationController.ts +++ b/src/controllers/AdminOrganizationController.ts @@ -77,24 +77,23 @@ export default class AdminOrganizationController { } static sendEmailToken(req: express.Request, res: express.Response) { - const path: string = __dirname + '/../../views/email/token.twig' Organization.findById(req.params.id).then(data => { if (data === null) { 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) => { - console.log(html) - console.log(err) - EmailService.send( - data.get('email'), - "Votre lien secret pour modifier votre association - Forum des associations 2020", - html - ) + EmailService.send( + data.get('email'), + "Votre lien secret pour modifier votre association - Forum des associations 2020", + "token", + { organizationName: data.get('adminName'), token: data.get('token') } + ).then(() => { + console.log('email sent') }) res.json({ success: true }) }) } + static resetToken(req: express.Request, res: express.Response) { Organization.updateOne({ _id: req.params.id }, { token: cryptoRandomString({ length: 10, type: 'distinguishable' }), diff --git a/test_mail.js b/test_mail.js new file mode 100644 index 0000000..0908028 --- /dev/null +++ b/test_mail.js @@ -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" ', + 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: + + // 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); \ No newline at end of file diff --git a/views/emails/token.twig b/views/emails/token.twig index e69de29..82df97b 100644 --- a/views/emails/token.twig +++ b/views/emails/token.twig @@ -0,0 +1,5 @@ +Bonjour gérant de l'association nommée "{{ organizationName }}" + +Voici votre clée: {{ token }} + +Coordialement \ No newline at end of file