0.0.2 • Published 2 years ago

@d-vc/mailer v0.0.2

Weekly downloads
-
License
-
Repository
github
Last release
2 years ago

@galicia-toolkit-nestjs/mailer

📝 Requerimientos básicos

🛠️ Instalar dependencia

npm install -S @galicia-toolkit-nestjs/mailer
yarn add @galicia-toolkit-nestjs/mailer

⚙️ Configuración

Importar el MailerModule en el archivo app.module.ts, y el módulo se encargará de obtener la configuración y realizar la connexion automáticamente.

//./src/app.module.ts
import { Module } from '@nestjs/common';
import { MailerModule } from "@galicia-toolkit-nestjs/mailer";

import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
    MailerModule.forRoot({
      transport: {
        host: process.env.EMAIL_HOST,
        port: parseInt(process.env.EMAIL_PORT, 10) || 587,
        secure: false,
        auth: {
          user: process.env.EMAIL_USER,
          pass: process.env.EMAIL_PASSWORD,
        },
      },
      defaults: {
        from: process.env.EMAIL_USER,
      },
      template: {
        dir: join(__dirname, './templates'),
        adapter: new HandlebarsAdapter(),
        options: {
          strict: true,
        },
      },
    })],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Inyectar el MailerService para poder realizar el envío de mails.

//./src/app.service.ts
import { MailerService } from '@galicia-toolkit-nestjs/mailer';

@Injectable()
export class AppService {
  constructor(private readonly mailerService: MailerService) {}

  async sendMail() {
    try {
      return await this.mailerService.sendMail({
        to: 'to <to@email.com>',
        from: 'from <from@email.com>',
        subject: 'Subject of mail',
        text: 'this is a plain text',
        html: '<b>this is a html email</b>',
      });
    } catch (error) {
      throw new Error(error.message);
    }
  }
}

Envío de mail con template

//./src/app.service.ts
import { MailerService } from '@galicia-toolkit-nestjs/mailer';

@Injectable()
export class AppService {
  constructor(private readonly mailerService: MailerService) {}

  async sendMail(email: string, name: string) {
    try {
      return await this.mailerService.sendMail({
        to: email,
        from: 'from <from@email.com>',
        subject: 'Greeting from NestJS NodeMailer',
        template: './email',
        context: {
          name: name,
        },
      });
    } catch (error) {
      throw new Error(error.message);
    }
  }
}

Email template

//templates/email.hbs
<p>Hi {{name}},</p>
<p>Hello from NestJS NodeMailer</p>