NEST JS 이메일 발송

Hy·2021년 7월 21일
0

공식 문서 : https://nest-modules.github.io/mailer/docs/mailer

  1. NPM 모듈 다운
1------
npm install --save @nestjs-modules/mailer nodemailer
2------
npm install --save handlebars
#or
npm install --save pug
#or
npm install --save ejs

2.Module에 mailerModule을 등록해준다.

//app.module.ts
import { Module } from '@nestjs/common';
import { MailerModule } from '@nestjs-modules/mailer';
import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter';

@Module({
  imports: [
    MailerModule.forRoot({
      transport: 'smtps://user@domain.com:pass@smtp.domain.com',
      defaults: {
        from: '"nest-modules" <modules@nestjs.com>',
      },
      template: {
        dir: __dirname + '/templates',
        adapter: new HandlebarsAdapter(),
        options: {
          strict: true,
        },
      },
    }),
  ],
})
export class AppModule {}

3.서비스 작성

// 생성자
constructor (
	private readonly mailerService: MailerService
){}

async sendMail(config){
	await this.mailerService.sendMail(config)
    //함수뒤에 then , catch함수등을 작성할 수 있다.
    return true;
}

async mailConfig(email){
	return{
    	to : 'hello@naver.com',
        from : 'hello_dev@vel.com',
        subject : '안녕하세요',
    	html : '<h1>안녕하세요</h1>',
        text : 'text'
        //...이외 옵션도 다양하니 찾아보세요!
    }
}
  1. controller에서 호출
@Get('/sendMail')
async sendMail(@Param('email') email ){
	const config = this.mailService.mailConfig(email);
    const result = await this.mailService.sendMail(config);
    return result;
}

결과 확인

profile
Hy

0개의 댓글