자동으로 메일 전송할 일이 생겨서 메일 관련 라이브러리를 찾아보다보니 편해 보여서 쓰게 되었다.

 

https://nest-modules.github.io/mailer/docs/mailer.html

 

NestJS - Mailer · Modules for the nestjs framework

Modules for the nestjs framework

nest-modules.github.io

yarn add @nestjs-modules/mailer nodemailer

#or

npm install --save @nestjs-modules/mailer nodemailer

 

nestjs에서 제공하는 사용법이다.

우선 mailer와 nodemailer를 설치하고,

텍스트 형식으로만 사용할 경우에는 위의 라이브러리만으로 메일을 전송할 수 있지만, templet을 사용할 예정이라면 다른 라이브러리도 설치해 줘야 된다.

 

npm

npm install --save handlebars
#or
npm install --save pug
#or
npm install --save ejs

yarn

yarn add handlebars
#or
yarn add pug
#or
yarn add ejs

 

여러 템플릿 엔진 종류 중에 사용하고 싶은 종류를 설치해서 사용하면 된다.

 

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

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

만약 템플릿을 사용하지 않을 것이라면, template 쪽을 제거하고 사용하면 된다.

 

우선 예시로 Ejs를 사용할 예정이기에 adapter에 Ejs가 포함되었다. 위의 형태는 nestjs에서 예시로 제공하는 향태이다.

 

MailerModule.forRootAsync({
      useFactory: () => ({
        transport: {
          host: process.env.MAIL_HOST,
          port: Number(process.env.MAIL_PORT),
          auth: {
            user: process.env.MAIL_ID,
            pass: process.env.MAIL_PASS,
          },
        },
        defaults: {
          from: `'${process.env.MAIL_FROM_NAME}' <${process.env.MAIL_FROM_AD}>`, //보낸사람
        },
        template: {
          dir: __dirname + "/templates",
          adapter: new EjsAdapter(),
          options: {
            strict: true,
          },
        },
      }),
    }),

 

현재 위의 코드는 내가 사용하기 위해서 나눈 코드이다. transport를 세분화했다. 사용할 메일의 pop3나 smtp 설정 쪽에 확인해 보면 host, port를 확인할 수 있고, auth에는 사용할 이메일의 아이디와 비밀번호를 입력하면 된다.

defaults에 입력되는 from은 보내는 사람의 이름 표기이다. 형태는    '아름' <메일주소>'   형태로 보내지 않으면 에러가 뜨니 주의하자.

 

위와 같이 기본 설정만해주고 template에 templates 위치를 지정해주면 된다.

 

mail 전송 라이브러리는 service 파일에서 

import { MailerService } from "@nestjs-modules/mailer";

@Injectable()
export class MailService {
  constructor(private readonly mailerService: MailerService) {}
  async sendMail(): Promise<T> {
    return await this.mailerService.sendMail({
      to: process.env.MAIL_TO,
      subject: "이 메일은 영국에서 시작되어",
      text: 'Hello World',
      html: <p>Hello World</p>
    });
  }
}

 

 

위와같이 설치해 놓은 라이브러리를 불러서 sendMail 함수를 통하여 메일을 전송할 수 있다.

to는 받는 이메일 주소,

subject는 제목,

template을 사용하지 않을 경우

text나 html을 작성하여 안에 내용을 작성하면 된다.

 

혹시 템플릿을 작성할 경우

import { MailerService } from "@nestjs-modules/mailer";

@Injectable()
export class MailService {
  constructor(private readonly mailerService: MailerService) {}
  async sendMail(): Promise<T> {
    return await this.mailerService.sendMail({
      to: process.env.MAIL_TO,
      subject: "이 메일은 영국에서 시작되어",
      template: "mailTest.ejs",
      context: {
        templetData: templetData,
      },
    });
  }
}

 

template 파일 위치는 module에 지정되어 있고, 파일 이름을 입력하고, 파일에 변수를 주입할 경우 context에 객체의 형태로 작성한다.

ejs에서 객체 이름을 통하여 사용할 수 있고, 만약 사용할 경우 locals. 객체명 형태로 사용가능하다.

 

다음에는 ejs의 간단한 사용법을 작성할 예정이다