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 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" <ne-pas-repondre@espacecondorcet.org>',
// 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<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()
})
})
}
}

View file

@ -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'

View file

@ -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
)
"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' }),

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