NestJS Mailer 사용해서 메일 보내기

like0·2022년 5월 24일
0

참고링크
참고링크
참고링크

🔅 설치하기

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

🔅 추가 설치 (선택적인 dependency이지만, template 사용하려면 설치해야 한다!)

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

🔅 모듈

imports:[
        MailerModule.forRootAsync({
            useFactory: () => ({
                transport: {
                    host: 'smtp.example.com',
                    port: 587,
                    auth: {
                        user: 'email address',
                        pass: 'password'
                    },
                },
                defaults: {
                    from: '"no-reply" <email address>',
                },
                preview: true,
				template: {
                  dir: __dirname + '/templates',
                  adapter: new PugAdapter(),
                  options: {
                    strict: true,
                  },
                },
            })
        }),
      ],
      
 //해당 코드는 async fonfiguration을 사용했으며, 사용하지 않는 것도 가능하다.

1️⃣ 만일 2단계 인증이 설정된 구글 계정을 통해 해당 기능을 이용한다면,
pass 해당링크 를 통해 생성한 비밀번호를 입력하면 된다.

2️⃣ defaults는 전송된 모든 메시지에 대해 설정되는 선택적 개체이다.
예를 들어 위의 코드처럼 from에 설정을 해두면,
service 파일에서 메일 보내는 이를 따로 명시하지 않았을 경우,
from에 설정된 값이 보내는 이로 표시된다.

3️⃣ preview를 true로 설정해두면, 브라우저를 통해 미리보기를 할 수 있다.

4️⃣ template은 말그대로 템플릿에 대한 설정이다.
예를 들어 특정 유저에게 보안코드를 보내기 위한 메일이라면, 그 형식이 매번 같을 것이다.

그리고 username, code라는 변수의 값만 할당하여 메일이 보내지도록 한다.

🔆 서비스

ex1)

this.mailerService
      .sendMail({
        to: 'test@nestjs.com', // list of receivers
        from: 'noreply@nestjs.com', // sender address
        subject: 'Testing Nest MailerModule ✔', // Subject line
        text: 'welcome', // plaintext body
        html: '<b>welcome</b>', // HTML body content
      })

템플릿을 사용한다면 다음과 같이 나타낼 수도 있다.

this.mailerProvider.sendMail({
  to: 'test@nestjs.com',
  from: 'noreply@nestjs.com',
  subject: 'Testing Nest Mailermodule with template ✔',
  template: 'welcome.html',
  context: {  // Data to be sent to template files.
    username: 'john doe',
    code: 'cf1a3f828287'
  }
})

위의 코드를 통해서 username과 code에는 각각 john doe'와 'cf1a3f828287'가 들어 갈것이다.

++ 파일 첨부

참고 링크
참고 링크

npm install nodemailer //설치한다
const options  = {
		to: 'test@nestjs.com', // list of receivers
        from: 'noreply@nestjs.com', // sender address
        subject: 'Testing Nest MailerModule ✔', // Subject line
        text: 'welcome', // plaintext body
        html: '<b>welcome</b>', // HTML body content
		attachments: [
            {   // utf-8 string as an attachment
                filename: 'text1.txt',
                content: 'hello world!'
            }
       	]
}

this.mailSerivce.sendMail(options)
profile
배우고 성장하는 개발자가 되기!

0개의 댓글