-
Notifications
You must be signed in to change notification settings - Fork 0
11. 인증 메일 전송
Jinho Kim edited this page Apr 18, 2023
·
3 revisions
npm i @nestjs-modules/mailer nodemailer
npm i ejs
import { MailerModule } from '@nestjs-modules/mailer';
import { EjsAdapter } from '@nestjs-modules/mailer/dist/adapters/ejs.adapter';
import * as path from 'path';
@Module({
imports: [
MailerModule.forRoot({
transport: {
service: 'gmail',
auth: {
user: process.env.NODEMAILER_USER,
pass: process.env.NODEMAILER_PASSWORD,
},
},
defaults: {
from: '"nest-modules" <[email protected]>',
},
template: {
dir: path.join(process.cwd(), 'src/auth/templates'),
adapter: new EjsAdapter(),
options: {
strict: true,
},
},
}),
],
...
transport
- service: 사용할 메일 서비스
도메인 주소가 들어가거나, 위 코드 처럼 구글 정보가 들어갈 수도 있음. - defaults: 전송할 메일의 제목
- template: 메일 내용 양식
보통 ejs, handlebars, pug 등을 사용하는데, npm trends 기준 사용자가 제일 많은 ejs를 사용하기로 함
구글 로그인 -> Google 계정 관리 -> 보안 -> Google에 로그인에서 2단계 인증설정 -> 앱 비밀 번호 설정
여기서 생성한 비밀번호를 module transport 객체에 넣어주면 된다.
아래 같은 형식으로 html로 메일 양식을 정해줄 수 있음.
<%= locals.code %> 같은 방식으로 메일 전송하는 함수에서 넣어준 데이터들을 사용할 수 있음.
<!DOCTYPE html>
<html>
<head>
<title>Verify Your Email Address</title>
</head>
<body>
<h1>Verify Your Email Address</h1>
<p>Thank you for signing up! Your verification code is:</p>
<p><strong><%= locals.code %></strong></p>
<p>Please enter this code on the verification page on our website.</p>
<p>If you did not sign up for our service, please ignore this email.</p>
</body>
</html>
async sendVerificationEmail(userId: string): Promise<void> {
const userEmail = await this.accountServce.getUserEmail(userId);
if (userEmail === null) {
throw new NotFoundException('Not found user email');
}
const code = Math.random().toString(36).substring(2, 15);
await this.mailService.sendMail({
to: userEmail.email,
subject: 'Verify Your Email Address',
template: 'verification',
context: {
code,
},
});
this.emailMap.set(userId, code);
}
mailService의 sendMail을 사용해서 메일을 전송함.
context 객체 안에 들어가는 데이터들이 ejs 파일안의 local 객체에 들어있음.
EX)
context: {
code,
}
-> <%= locals.code %> 같은 식으로 사용