Cambios en servicio mailer

This commit is contained in:
Joan Sanchez 2017-05-31 14:55:41 +02:00
parent 552559adaa
commit a4d8574321
8 changed files with 55 additions and 64 deletions

View File

@ -7,13 +7,11 @@ var template = require('../template.js');
// Escrito de cambios en méto de pago del cliente
router.post('/paymentUpdate', function(request, response) {
database.pool.query('SELECT Cliente, `e-mail` AS email FROM Clientes WHERE Id_Cliente = ?', [request.body.user], function(error, rs) {
//Datos del escrito
// Datos del escrito
var params = {
clientName: rs[0].Cliente
};
//Obtener plantilla y enviar
// Obtener plantilla y enviar
template.getTemplate('paymentUpdate', 'es', params, function(tplResult) {
if (mail.send({recipient: rs[0].email, subject: tplResult.subject, body: tplResult.body})) {
response.json({status: "OK"});

View File

@ -1,13 +1,4 @@
var Settings = require('../Settings.js');
module.exports = {
/**
* Imprimir cabecera
*/
printHeader: function() {
console.log('##########################################################');
console.log('## ' + Settings.name + ' ##');
console.log('##########################################################');
}
};

View File

@ -1,6 +1,7 @@
var fs = require('fs');
var settings = require('./settings.js');
var logger = require('./logger.js');
var path = require('path');
module.exports = {
@ -12,12 +13,14 @@ module.exports = {
*/
load: function(templateName, langCode) {
// Comprobamos que exista una traducción para esta plantilla
if (fs.existsSync('./Application/Language/' + langCode + '.' + templateName + '.json')) {
return require('./Language/' + langCode + '.' + templateName + '.json');
} else if(fs.existsSync('./Application/Language/' + settings.defaultLanguage + '.' + templateName + '.json')){
return require('./Language/' + settings.defaultLanguage + '.' + templateName + '.json');
var localeFile = path.join(__dirname, 'Language', `${langCode}.${templateName}.json`);
var defaultLocaleFile = path.join(__dirname, 'Language', `${settings.defaultLanguage}.${templateName}.json`);
if (fs.existsSync(localeFile)) {
return require(localeFile);
} else if (fs.existsSync(defaultLocaleFile)) {
return require(defaultLocaleFile);
} else {
logger.print(__LOG_ERROR, 'No se ha encontrado ninguna traducción para la plantilla ' + templateName + '.');
throw new Error('No se ha encontrado ninguna traducción para la plantilla ' + templateName + '.');
}
}
}
};

View File

@ -1,6 +1,7 @@
var nodemailer = require('nodemailer');
var settings = require('./settings.js');
var logger = require('./logger.js');
var path = require('path');
// Módulo para el envío de emails
module.exports = {
@ -28,28 +29,29 @@ module.exports = {
* @param {Object} data - Datos para el envío del email
*/
send: function(data) {
var filePath = 'Template/images/';
let mailOptions = {
from: '"' + settings.app().senderName + '" <' + settings.app().senderMail + '>',
to: data.recipient,
subject: data.subject,
html: data.body,
attachments: [
{filename: 'header.png', path: './Application/Template/images/header.png', cid: 'header'},
{filename: 'arrow.png', path: './Application/Template/images/arrow.png', cid: 'arrow'},
{filename: 'chat.png', path: './Application/Template/images/chat.png', cid: 'chat'},
{filename: 'facebook.png', path: './Application/Template/images/facebook.png', cid: 'facebook'},
{filename: 'twitter.png', path: './Application/Template/images/twitter.png', cid: 'twitter'},
{filename: 'youtube.png', path: './Application/Template/images/youtube.png', cid: 'youtube'},
{filename: 'pinterest.png', path: './Application/Template/images/pinterest.png', cid: 'pinterest'},
{filename: 'instagram.png', path: './Application/Template/images/instagram.png', cid: 'instagram'},
{filename: 'linkedin.png', path: './Application/Template/images/linkedin.png', cid: 'linkedin'}
{filename: 'header.png', path: path.join(__dirname, filePath, 'header.png'), cid: 'header'},
{filename: 'arrow.png', path: path.join(__dirname, filePath, 'arrow.png'), cid: 'arrow'},
{filename: 'chat.png', path: path.join(__dirname, filePath, 'chat.png'), cid: 'chat'},
{filename: 'facebook.png', path: path.join(__dirname, filePath, 'facebook.png'), cid: 'facebook'},
{filename: 'twitter.png', path: path.join(__dirname, filePath, 'twitter.png'), cid: 'twitter'},
{filename: 'youtube.png', path: path.join(__dirname, filePath, 'youtube.png'), cid: 'youtube'},
{filename: 'pinterest.png', path: path.join(__dirname, filePath, 'pinterest.png'), cid: 'pinterest'},
{filename: 'instagram.png', path: path.join(__dirname, filePath, 'instagram.png'), cid: 'instagram'},
{filename: 'linkedin.png', path: path.join(__dirname, filePath, 'linkedin.png'), cid: 'linkedin'}
]
};
this.transporter.sendMail(mailOptions, (error, info) => {
if (error) {
logger.print(__LOG_ERROR, error);
} else if (settings.debug) {
} else if (settings.app().debug) {
logger.print(__LOG_INFO, 'Se ha enviado el email ' + info.messageId + ' [' + info.response + ']');
return true;

View File

@ -4,7 +4,7 @@ var settings = require('./settings.js');
// Página por defecto
router.get('/', function(request, response) {
response.send(Settings.name + ' v' + settings.version);
response.send(settings.app().name + ' v' + settings.app().version);
});
// Rutas de los escritos.

View File

@ -3,6 +3,7 @@ module.exports = {
/**
* Configuración de la aplicación
* @return {Object} Objeto de configuración app
*/
app: function() {
return require('./Config/mailerApp.json');
@ -10,6 +11,7 @@ module.exports = {
/**
* Configuración de smtp
* @return {Object} Objeto de configuración smtp
*/
smtp: function() {
return require('./Config/mailerSmtp.json');
@ -17,6 +19,7 @@ module.exports = {
/**
* Configuración de mysql
* @return {Object} Objeto de configuración MySQL
*/
mysql: function() {
return require('./Config/mailerMysql.json');

View File

@ -1,43 +1,39 @@
var fs = require('fs');
var mustache = require('mustache');
var database = require('./database.js');
var logger = require('./logger.js');
var language = require('./language.js');
var path = require('path');
var Template = {
/**
* Obtiene la plantilla
* @param {String} templateName - Nombre de la plantilla
* @param {Object} langCode - Código del idioma
* @param {Object} params - Datos a reemplazar.
* @param {Object} callback - Callback
*/
getTemplate: function(templateName, langCode, params, callback) {
database.pool.query('SELECT name, attachmentPath FROM vn.mailTemplates WHERE name = ?', [templateName], function(error, rs)
{
database.pool.query('SELECT name, attachmentPath FROM vn.mailTemplates WHERE name = ?', [templateName], function(error, rs) {
// Comprobamos que exista la plantilla
if (rs.length == 0) {
logger.print(__LOG_ERROR, 'La plantilla ' + templateName + ' no existe');
return;
}
if (rs.length == 0)
throw new Error('La plantilla ' + templateName + ' no existe');
var langParams = language.load(templateName, langCode);
params = Object.assign({}, langParams, params);
var path = './Application/Template/' + rs[0].name + '.html';
var templatePath = path.join(__dirname, 'Template', `${rs[0].name}.html`);
if (!fs.existsSync(path)) {
logger.print(__LOG_ERROR, 'No se ha podido cargar la plantilla ' + name + '.html');
} else {
Template.render(path, params, function(tplBody) {
callback({subject: params.subject, body: tplBody});
});
}
if (!fs.existsSync(templatePath))
throw new Error('No se ha podido cargar la plantilla ' + templateName + '.html');
Template.render(templatePath, params, function(tplBody) {
callback({subject: params.subject, body: tplBody});
});
});
},
/**
* Renderiza las plantillas
* @param {String} path - Ruta de la plantilla
* @param {String} language - Idioma
* @param {Object} params - Listado de parámetros a remplazar
* @param {Object} callback - Callback
*/
@ -46,7 +42,7 @@ var Template = {
mustache.parse(body);
callback(mustache.render(body, params));
});
},
}
};
module.exports = Template;

View File

@ -2,14 +2,13 @@
* Módulos necesarios
*/
var express = require('express');
var app = express();
var app = module.exports = express();
var bodyParser = require('body-parser');
var settings = require('./Application/settings.js');
var mail = require('./Application/mail.js');
var logger = require('./Application/logger.js');
var database = require('./Application/database.js');
var terminal = require('./Application/Util/terminal.js');
// Middleware
app.use(bodyParser.json());
@ -19,20 +18,19 @@ app.use(bodyParser.urlencoded({extended: true}));
app.use('/', require('./Application/router.js'));
// Iniciar escucha del servidor
app.listen(settings.app().port, function() {
// Imprimir cabecera
terminal.printHeader();
app.start = function() {
return app.listen(settings.app().port, function() {
mail.init();
database.init();
logger.print(__LOG_INFO, 'Servidor de correo iniciado en el puerto ' + settings.app().port);
if (settings.app().debug) {
logger.print(__LOG_WARNING, 'El modo debug está activado');
}
});
};
// Escucha SMTP
mail.init();
if (require.main === module) {
app.start();
}
// Iniciar base de datos
database.init();
logger.print(__LOG_INFO, 'Servidor de correo iniciado en el puerto ' + settings.app().port);
if (settings.debug) {
logger.print(__LOG_WARNING, 'El modo debug está activado');
}
});