Envió de archivos listo
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
describe('AppController', () => {
|
||||
let appController: AppController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const app: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
}).compile();
|
||||
|
||||
appController = app.get<AppController>(AppController);
|
||||
});
|
||||
|
||||
describe('root', () => {
|
||||
it('should return "Hello World!"', () => {
|
||||
expect(appController.getHello()).toBe('Hello World!');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
@Controller()
|
||||
export class AppController {
|
||||
constructor(private readonly appService: AppService) {}
|
||||
|
||||
@Get()
|
||||
getHello(): string {
|
||||
return this.appService.getHello();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
import { MailModule } from './mail/mail.module';
|
||||
@Module({
|
||||
imports: [MailModule],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
getHello(): string {
|
||||
return 'Hello World!';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import {
|
||||
Controller,
|
||||
Post,
|
||||
Body,
|
||||
UploadedFile,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import { MailService } from './mail.service';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import * as fs from 'fs';
|
||||
import * as csv from 'csv-parser';
|
||||
import { diskStorage } from 'multer'; // Importar para almacenar en el sistema de archivos
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Mail') // Grupo de endpoints
|
||||
@Controller('mail')
|
||||
export class MailController {
|
||||
constructor(private readonly mailService: MailService) {}
|
||||
|
||||
// Endpoint para enviar correos a través de una solicitud POST
|
||||
@Post('send')
|
||||
async sendMail(@Body() body: { to: string; subject: string; text: string }) {
|
||||
const { to, subject, text } = body;
|
||||
|
||||
const result = await this.mailService.sendMail(to, subject, text);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Post('send-bulk')
|
||||
//@UseInterceptors(FileInterceptor('file'))
|
||||
@UseInterceptors(
|
||||
FileInterceptor('file', {
|
||||
storage: diskStorage({
|
||||
destination: './uploads', // Carpeta donde guardar los archivos
|
||||
filename: (req, file, cb) => {
|
||||
// Guardar el archivo con su nombre original
|
||||
const filename = file.originalname;
|
||||
cb(null, filename);
|
||||
},
|
||||
}),
|
||||
}),
|
||||
)
|
||||
async sendBulkMails(@UploadedFile() file: Express.Multer.File) {
|
||||
const emails: string[] = [];
|
||||
const subject = 'Correo de prueba';
|
||||
const text = 'Este es un correo enviado de manera masiva.';
|
||||
|
||||
// Leer el archivo CSV
|
||||
return new Promise((resolve, reject) => {
|
||||
fs.createReadStream(file.path)
|
||||
.pipe(csv())
|
||||
.on('data', (row) => {
|
||||
emails.push(row.email); // Agregar cada correo a la lista
|
||||
})
|
||||
.on('end', async () => {
|
||||
// Enviar correos en bulk usando el servicio de correos
|
||||
const result = await this.mailService.sendBulkMails(
|
||||
emails,
|
||||
subject,
|
||||
text,
|
||||
);
|
||||
resolve(result);
|
||||
})
|
||||
.on('error', (error) => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MailService } from './mail.service';
|
||||
import { MailController } from './mail.controller';
|
||||
|
||||
@Module({
|
||||
providers: [MailService],
|
||||
controllers: [MailController],
|
||||
exports: [MailService], // Exportar si otros módulos necesitan usar el MailService
|
||||
})
|
||||
export class MailModule {}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import * as nodemailer from 'nodemailer';
|
||||
import * as dotenv from 'dotenv';
|
||||
dotenv.config();
|
||||
|
||||
@Injectable()
|
||||
export class MailService {
|
||||
private transporter;
|
||||
|
||||
constructor() {
|
||||
|
||||
|
||||
this.transporter = nodemailer.createTransport({
|
||||
service: 'gmail',
|
||||
auth: {
|
||||
user: process.env.USER_GMAIL, // tu dirección de correo de Gmail
|
||||
pass: process.env.PASS_GMAIL, // contraseña de aplicación generada en Google
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
/*
|
||||
this.transporter = nodemailer.createTransport({
|
||||
host: 'localhost',
|
||||
port: 1025,
|
||||
ignoreTLS: true,
|
||||
});
|
||||
*/
|
||||
}
|
||||
|
||||
// Función para generar el reporte de correos enviados y fallidos
|
||||
private generateReport(
|
||||
sentEmails: string[],
|
||||
failedEmails: { email: string; error: any }[],
|
||||
totalTime: number,
|
||||
) {
|
||||
console.log('--- Reporte de envío de correos ---');
|
||||
console.log(`Tiempo total de envío: ${totalTime} segundos`);
|
||||
|
||||
console.log('\nCorreos enviados con éxito:');
|
||||
sentEmails.forEach((email) => console.log(email));
|
||||
|
||||
console.log('\nCorreos fallidos:');
|
||||
failedEmails.forEach((failed) =>
|
||||
console.log(`Correo: ${failed.email} - Error: ${failed.error.message}`),
|
||||
);
|
||||
|
||||
console.log(`\nTotal de correos enviados: ${sentEmails.length}`);
|
||||
console.log(`Total de correos fallidos: ${failedEmails.length}`);
|
||||
|
||||
if (failedEmails.length > 0) {
|
||||
console.log(
|
||||
'\nAlgunos correos fallaron. Inténtalos de nuevo de manera manual.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async sendMail(to: string, subject: string, text: string) {
|
||||
const mailOptions = {
|
||||
from: process.env.USER_GMAIL,
|
||||
to,
|
||||
subject,
|
||||
text,
|
||||
};
|
||||
|
||||
return this.transporter.sendMail(mailOptions);
|
||||
}
|
||||
|
||||
async sendBulkMailsOld(emails: string[], subject: string, text: string) {
|
||||
const batchSize = 100; // Número de correos por lote
|
||||
for (let i = 0; i < emails.length; i += batchSize) {
|
||||
const batch = emails.slice(i, i + batchSize);
|
||||
const promises = batch.map((email) =>
|
||||
this.transporter.sendMail({
|
||||
from: process.env.USER_GMAIL,
|
||||
to: email,
|
||||
subject,
|
||||
text,
|
||||
}),
|
||||
);
|
||||
|
||||
// Esperar que se envíen todos los correos del lote
|
||||
await Promise.all(promises);
|
||||
|
||||
// Delay entre lotes para no sobrecargar el servidor de Gmail
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000)); // 2 segundos de pausa
|
||||
}
|
||||
}
|
||||
|
||||
async sendBulkMails(emails: string[], subject: string, text: string) {
|
||||
const batchSize = 100;
|
||||
const sentEmails: string[] = [];
|
||||
const failedEmails: { email: string; error: any }[] = [];
|
||||
const startTime = Date.now(); // Inicia el temporizador
|
||||
|
||||
for (let i = 0; i < emails.length; i += batchSize) {
|
||||
const batch = emails.slice(i, i + batchSize);
|
||||
const promises = batch.map(async (email) => {
|
||||
try {
|
||||
await this.transporter.sendMail({
|
||||
from: process.env.USER_GMAIL,
|
||||
to: email,
|
||||
subject,
|
||||
text,
|
||||
});
|
||||
sentEmails.push(email); // Agregar a lista de enviados exitosamente
|
||||
} catch (error) {
|
||||
|
||||
failedEmails.push({ email, error }); // Agregar a lista de fallos
|
||||
}
|
||||
});
|
||||
|
||||
// Espera a que todos los correos del lote se envíen
|
||||
await Promise.all(promises);
|
||||
|
||||
// Delay para evitar saturar el servidor de correo
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
}
|
||||
|
||||
const totalTime = (Date.now() - startTime) / 1000; // Tiempo total en segundos
|
||||
|
||||
// Generar el reporte final
|
||||
this.generateReport(sentEmails, failedEmails, totalTime);
|
||||
}
|
||||
|
||||
async retryFailedEmails(
|
||||
failedEmails: { email: string; error: any }[],
|
||||
subject: string,
|
||||
text: string,
|
||||
) {
|
||||
const retrySuccess: string[] = [];
|
||||
const retryFailed: { email: string; error: any }[] = [];
|
||||
|
||||
for (const failed of failedEmails) {
|
||||
try {
|
||||
await this.transporter.sendMail({
|
||||
from: process.env.USER_GMAIL,
|
||||
to: failed.email,
|
||||
subject,
|
||||
text,
|
||||
});
|
||||
retrySuccess.push(failed.email); // Reintento exitoso
|
||||
} catch (error) {
|
||||
|
||||
retryFailed.push({ email: failed.email, error }); // Reintento fallido
|
||||
}
|
||||
}
|
||||
|
||||
console.log('--- Reintento de correos fallidos ---');
|
||||
console.log('\nCorreos reenviados con éxito:');
|
||||
retrySuccess.forEach((email) => console.log(email));
|
||||
|
||||
console.log('\nCorreos que fallaron nuevamente:');
|
||||
retryFailed.forEach((failed) =>
|
||||
console.log(`Correo: ${failed.email} - Error: ${failed.error.message}`),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
await app.listen(process.env.PORT ?? 3000);
|
||||
}
|
||||
bootstrap();
|
||||
Reference in New Issue
Block a user