카테고리 없음

Nest.js 메일인증 구현

index.ys 2023. 8. 13. 23:39

1.app.module.ts에 메일 인증 import

  • mail전송 기본 설정 import
 MailerModule.forRootAsync({
      useFactory: () => ({
        transport: {
          host: process.env.EMAILHOST,
          port: +process.env.EMAILPORT,
          auth: {
            user: process.env.EMAILADDRESS,
            pass: process.env.EMAILPASSWORD,
          },
        },
        defaults: {
          from: '"nest-modules" <modules@nestjs.com>',
        },
        template: {
          dir: __dirname + '/templates',
          adapter: new EjsAdapter(),
          options: {
            strict: true,
          },
        },
      }),
    }),

2. controller계층에 메일인증 메서드 선언

  @Post('/authcode')
  async verifyEmailSend(
    @Body() verifyEmailDto: VerifyEmailDto,
  ): Promise<number> {
    const { email } = verifyEmailDto;
    return await this.usersService.verifyEmailSend(email);
  }

3. service계층에 비즈니스 로직 작성

  async verifyEmailSend(email: string): Promise<number> {
    try {
      const authcode: number = await this.createEmailCode();
      console.log(authcode);
      await this.mailerService.sendMail({
        to: email, // 수신자이메일 수조
        from: 'ystar5008@naver.com', // 발신자 이메일 주소
        subject: '이메일 인증 요청 메일입니다.', // 제목
        html: '4자리 인증 코드 : ' + `<b> ${authcode}</b>`, // 내용
      });
      return authcode;
    } catch (err) {
      throw new InternalServerErrorException(
        '이메일 전송 중 오류가 발생했습니다.',
      );
    }
  }