Skip to content

Commit 3c7e108

Browse files
authored
Merge pull request #1 from jreyesdev/develop
Develop
2 parents b237668 + e9b43d1 commit 3c7e108

File tree

7 files changed

+136
-3
lines changed

7 files changed

+136
-3
lines changed

.env.example

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
DB_HOST=
2+
DB_PORT=
3+
DB_DATABASE=
4+
DB_USERNAME=
5+
DB_PASSWORD=
6+
7+
MAIL_FROM=
8+
MAIL_PASS=
9+
MAIL_CC=
10+
MAIL_TOSENT=

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
# Enviar CSV por email
2-
Scrip de NodeJs para enviar un archivo .CSV por correo electrónico
2+
Script de NodeJs para enviar un archivo .CSV por correo electrónico
33

44
### Pre-requisitos 📋
55

66
_Antes que continúes debes tener instalado:_
77

8-
* [NodeJS](https://nodejs.org) - _utilicé v12.6.2_
9-
* [npm](https://www.npmjs.com/) - _utilicé v6.14.4_
8+
* [NodeJS](https://nodejs.org) - _v12.6.2 o superior_
9+
* [npm](https://www.npmjs.com/) - _v6.14.4 o superior_
1010

1111
## Instalación 🔧
1212
Sigue estos pasos:

public/.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
*
2+
!.gitignore

src/database.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
const { Pool } = require('pg')
2+
3+
module.exports = new Pool({
4+
host: process.env.DB_HOST,
5+
port: process.env.DB_PORT,
6+
database: process.env.DB_DATABASE,
7+
user: process.env.DB_USERNAME,
8+
password: process.env.DB_PASSWORD
9+
})

src/file.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const path = require('path')
2+
const fs = require('fs')
3+
const csv = require('fast-csv')
4+
5+
// Archivo a enviar
6+
const creaArchivo = async (c,data) => {
7+
const dirFile = path.resolve(__dirname,'../public'),
8+
nameFile = 'usuarios_' + new Date().toLocaleDateString() + '.csv'
9+
pathFile = dirFile + '/' + nameFile
10+
let file
11+
c('Creando archivo...')
12+
fs.createWriteStream(pathFile).close()
13+
c('Archivo creado: ' + nameFile)
14+
c('Escribiendo datos...')
15+
file = await csv.writeToPath(pathFile, data, { headers: true })
16+
file.close()
17+
c('Archivo guardado exitosamente')
18+
c('Ubicación: ' + pathFile)
19+
return { pathFile, nameFile }
20+
}
21+
22+
module.exports = creaArchivo

src/index.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const dotenv = require('dotenv').config()
2+
3+
if(dotenv.error) throw dotenv.error
4+
5+
const c = con => console.log(con)
6+
7+
const pool = require('./database')
8+
const enviaEmail = require('./mail')
9+
10+
// Obtiene usuarios de BBDD para datos del archivo
11+
const getUsers = async () => {
12+
c('Consultando datos...')
13+
const { rows } = await pool.query('SELECT * FROM auth.users')
14+
c(`Consulta exitosa con ${rows.length} filas`)
15+
pool.end()
16+
return rows
17+
}
18+
19+
(async () => {
20+
const users = await getUsers()
21+
enviaEmail(c,users)
22+
})()

src/mail.js

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
const mailer = require('nodemailer')
2+
const file = require('./file')
3+
4+
const subject = 'Listado de usuarios hasta la fecha ' + new Date().toLocaleDateString()
5+
6+
const html = 'Mensaje...';
7+
8+
const confTransp = {
9+
host: 'smtp.gmail.com',
10+
port: 465,
11+
service: 'gmail',
12+
secure: true,
13+
auth: {
14+
user: process.env.MAIL_FROM,
15+
pass: process.env.MAIL_PASS
16+
}
17+
}
18+
19+
let options = {
20+
from: process.env.MAIL_FROM,
21+
cc: process.env.MAIL_CC,
22+
to: process.env.MAIL_TOSENT,
23+
subject,
24+
html,
25+
attachments: [
26+
{
27+
path: '',
28+
filename: '',
29+
}
30+
]
31+
}
32+
33+
// Envia email
34+
const enviaEmail = async (c,data) => {
35+
36+
const transport = mailer.createTransport(confTransp)
37+
38+
c('Validando datos...')
39+
40+
if(!data.length){
41+
options.attachments = null
42+
options.cc = null
43+
options.to = options.from
44+
options.subject = 'Error en consulta de usuarios'
45+
options.html = `Es probable que la lista esté vacía o error al ejecutar la consulta`
46+
c(`${options.subject}. ${options.html}`)
47+
}else{
48+
// Crea archivo
49+
const { pathFile, nameFile } = await file(c,data)
50+
options.attachments[0].path = pathFile
51+
options.attachments[0].filename = nameFile
52+
}
53+
54+
c('Enviando correo electronico...')
55+
56+
const resp = await transport.sendMail(options,(err,info)=>{
57+
if(err){
58+
c('Error al enviar correo:')
59+
return console.error(err.message)
60+
}
61+
c('Archivo enviado existosamente')
62+
c(info.messageId)
63+
})
64+
65+
return resp
66+
}
67+
68+
module.exports = enviaEmail

0 commit comments

Comments
 (0)