diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..b8b82fb --- /dev/null +++ b/.env.example @@ -0,0 +1,10 @@ +DB_HOST= +DB_PORT= +DB_DATABASE= +DB_USERNAME= +DB_PASSWORD= + +MAIL_FROM= +MAIL_PASS= +MAIL_CC= +MAIL_TOSENT= \ No newline at end of file diff --git a/README.md b/README.md index e6d023f..173a8a5 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ # Enviar CSV por email -Scrip de NodeJs para enviar un archivo .CSV por correo electrónico +Script de NodeJs para enviar un archivo .CSV por correo electrónico ### Pre-requisitos 📋 _Antes que continúes debes tener instalado:_ -* [NodeJS](https://nodejs.org) - _utilicé v12.6.2_ -* [npm](https://www.npmjs.com/) - _utilicé v6.14.4_ +* [NodeJS](https://nodejs.org) - _v12.6.2 o superior_ +* [npm](https://www.npmjs.com/) - _v6.14.4 o superior_ ## Instalación 🔧 Sigue estos pasos: diff --git a/public/.gitignore b/public/.gitignore new file mode 100644 index 0000000..c96a04f --- /dev/null +++ b/public/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore \ No newline at end of file diff --git a/src/database.js b/src/database.js new file mode 100644 index 0000000..f331c60 --- /dev/null +++ b/src/database.js @@ -0,0 +1,9 @@ +const { Pool } = require('pg') + +module.exports = new Pool({ + host: process.env.DB_HOST, + port: process.env.DB_PORT, + database: process.env.DB_DATABASE, + user: process.env.DB_USERNAME, + password: process.env.DB_PASSWORD +}) \ No newline at end of file diff --git a/src/file.js b/src/file.js new file mode 100644 index 0000000..b332bbd --- /dev/null +++ b/src/file.js @@ -0,0 +1,22 @@ +const path = require('path') +const fs = require('fs') +const csv = require('fast-csv') + +// Archivo a enviar +const creaArchivo = async (c,data) => { + const dirFile = path.resolve(__dirname,'../public'), + nameFile = 'usuarios_' + new Date().toLocaleDateString() + '.csv' + pathFile = dirFile + '/' + nameFile + let file + c('Creando archivo...') + fs.createWriteStream(pathFile).close() + c('Archivo creado: ' + nameFile) + c('Escribiendo datos...') + file = await csv.writeToPath(pathFile, data, { headers: true }) + file.close() + c('Archivo guardado exitosamente') + c('Ubicación: ' + pathFile) + return { pathFile, nameFile } +} + +module.exports = creaArchivo \ No newline at end of file diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..bb6274f --- /dev/null +++ b/src/index.js @@ -0,0 +1,22 @@ +const dotenv = require('dotenv').config() + +if(dotenv.error) throw dotenv.error + +const c = con => console.log(con) + +const pool = require('./database') +const enviaEmail = require('./mail') + +// Obtiene usuarios de BBDD para datos del archivo +const getUsers = async () => { + c('Consultando datos...') + const { rows } = await pool.query('SELECT * FROM auth.users') + c(`Consulta exitosa con ${rows.length} filas`) + pool.end() + return rows +} + +(async () => { + const users = await getUsers() + enviaEmail(c,users) +})() diff --git a/src/mail.js b/src/mail.js new file mode 100644 index 0000000..d1f156a --- /dev/null +++ b/src/mail.js @@ -0,0 +1,68 @@ +const mailer = require('nodemailer') +const file = require('./file') + +const subject = 'Listado de usuarios hasta la fecha ' + new Date().toLocaleDateString() + +const html = 'Mensaje...'; + +const confTransp = { + host: 'smtp.gmail.com', + port: 465, + service: 'gmail', + secure: true, + auth: { + user: process.env.MAIL_FROM, + pass: process.env.MAIL_PASS + } +} + +let options = { + from: process.env.MAIL_FROM, + cc: process.env.MAIL_CC, + to: process.env.MAIL_TOSENT, + subject, + html, + attachments: [ + { + path: '', + filename: '', + } + ] +} + +// Envia email +const enviaEmail = async (c,data) => { + + const transport = mailer.createTransport(confTransp) + + c('Validando datos...') + + if(!data.length){ + options.attachments = null + options.cc = null + options.to = options.from + options.subject = 'Error en consulta de usuarios' + options.html = `Es probable que la lista esté vacía o error al ejecutar la consulta` + c(`${options.subject}. ${options.html}`) + }else{ + // Crea archivo + const { pathFile, nameFile } = await file(c,data) + options.attachments[0].path = pathFile + options.attachments[0].filename = nameFile + } + + c('Enviando correo electronico...') + + const resp = await transport.sendMail(options,(err,info)=>{ + if(err){ + c('Error al enviar correo:') + return console.error(err.message) + } + c('Archivo enviado existosamente') + c(info.messageId) + }) + + return resp +} + +module.exports = enviaEmail \ No newline at end of file