Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
DB_HOST=
DB_PORT=
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=

MAIL_FROM=
MAIL_PASS=
MAIL_CC=
MAIL_TOSENT=
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -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:
Expand Down
2 changes: 2 additions & 0 deletions public/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*
!.gitignore
9 changes: 9 additions & 0 deletions src/database.js
Original file line number Diff line number Diff line change
@@ -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
})
22 changes: 22 additions & 0 deletions src/file.js
Original file line number Diff line number Diff line change
@@ -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
22 changes: 22 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -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)
})()
68 changes: 68 additions & 0 deletions src/mail.js
Original file line number Diff line number Diff line change
@@ -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