[Nest.js] nodemailer

2021. 8. 19. 00:35Nest.js

반응형

이번에는 express에서 사용하는 nodemailer를 nestjs에서 사용 하는 방법에 대해서 알아 볼 거다.

 

import { MailerModule } from '@nestjs-modules/mailer';
import { CACHE_MANAGER, Module } from '@nestjs/common';
import { SendmailService } from './sendmail.service';
import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter';
import { CacheModule } from '@nestjs/common';
import * as redisStore from 'cache-manager-ioredis';
import { TwilioModule } from 'nestjs-twilio';

@Module({
  imports: [
    TwilioModule.forRoot({
      accountSid: 'ACCOUNT SID값 입력',
      authToken: 'AUTH TOKEN 값 입력',
    }),
    CacheModule.register({
      store: redisStore,
      host: 'localhost',
      port: 6379,
    }),
    MailerModule.forRoot({
      transport: {
        host: 'smtp.gmail.com',
        port: 587,
        auth: {
          user: '보내는 사람의 이메일',
          pass: '위 이메일 계정의 비밀번호',
        },
      },
      preview: false,
      template: {
        dir: process.cwd() + '/template/',
        adapter: new HandlebarsAdapter(), // or new PugAdapter() or new EjsAdapter()
        options: {
          strict: true,
        },
      },
    }),
  ],
  providers: [SendmailService],
  exports: [SendmailService],
})
export class SendmailModule {}

module.ts에서 imports를 해준다

그리고 service 로직을 보자

import { MailerService } from '@nestjs-modules/mailer';
import { InjectTwilio, TwilioClient } from 'nestjs-twilio';
import { CACHE_MANAGER, Inject } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { Cache } from 'cache-manager';

@Injectable()
export class SendmailService {
  constructor(
    private readonly mailerService: MailerService,
    @Inject(CACHE_MANAGER) private cacheManager: Cache,
    @InjectTwilio() private readonly client: TwilioClient,
  ) {}

 
  public async sendMail(toEmail: string) {
    const randomNumber: number = Math.random() * 101;
    console.log('randomNumber: ', randomNumber);
    const value = await this.cacheManager.set(`${toEmail}`, randomNumber, {
      ttl: 5,
    });
    const returnValue = await this.cacheManager.get(`${toEmail}`);
    console.log(returnValue);
    this.mailerService
      .sendMail({
        to: `${toEmail}`, // list of receivers
        from: '보내는 사람의 이메일', // sender address
        subject: '가입을 환영합니다 🏃💨 ✔', // Subject line
        text: 'welcome nodemailer ', // plaintext body
        html: `<b>회원 가입을 환영합니다.</b> <div>인증 번호: ${returnValue}</div>`, // HTML body content
      })
      .then(() => {
        console.log(`success`);
      })
      .catch(() => {
        console.log(`fail`);
      });
  }
}
반응형

'Nest.js' 카테고리의 다른 글

[nest.js] TypeORM 정리  (0) 2021.08.24
[Nest.js] redis 연동  (0) 2021.08.10
[Nest.js] Swagger사용 방법  (0) 2021.07.30
[Nest.js] first step  (0) 2021.07.20