-
[ NestJS ] nodemailer로 메일 발송하기Topic/Node.js | server 2023. 7. 23. 10:45반응형
NestJS 프레임워크에서 이메일 발송을 위한 nodemailer 라이브러리를 적용하는 방법입니다.
nodemailer 사용 방법
- nodemailer 설치
npm install nodemailer
- 환경변수 설정 (.env)
# /.env email_host = "smtp.gmail.com" email_port = "777" email_client_id = '1234-abcd.apps.googleusercontent.com' email_secret = '1q2w3e4r' email_user = 'noreply@‘test.io email_address_from = 'help@test.io’ email_refresh_token = 'aaa' email_access_token = 'bbb'
- Mailer Service 생성 (service)
/** /src/email/mailer.service.ts * */ import { BadRequestException, Injectable } from '@nestjs/common'; import * as nodemailer from 'nodemailer'; @Injectable() export class MailerService { private readonly transporter: nodemailer.Transporter; constructor() { this.transporter = nodemailer.createTransport({ service: 'Gmail', secure: true, auth: { type: 'OAuth2', user: process.env.email_user, clientId: process.env.email_client_id, clientSecret: process.env.email_secret, refreshToken: process.env.email_refresh_token, accessToken: process.env.email_access_token, }, }); } async sendEmail(to: string, subject: string, html: string): Promise<void> { const sendSuccess = await this.transporter.sendMail({ from: { name: 'letsee', address: process.env.email_address_from, }, to, subject, html, }); if (!sendSuccess) { throw new BadRequestException('send email error'); } } }
- Mailer Service 사용 (controller)
/** /src/email/email.controller.ts * */ import { Controller, Post, Body } from '@nestjs/common'; import { MailerService } from './mailer.service'; @Controller('email') export class EmailController { constructor(private readonly mailerService: MailerService) {} @Post('send') async sendEmail( @Body() data: { to: string; subject: string; html: string }, ): Promise<string> { await this.mailerService.sendEmail(data.to, data.subject, data.html); return 'Email sent successfully'; } }
반응형'Topic > Node.js | server' 카테고리의 다른 글
[ NestJS ] AWS SES 적용 오류 (0) 2023.07.29 [ NestJS ] firstValueFrom과 lastValueFrom의 차이 (feat. RXJS) (0) 2023.07.15 [ NestJS ] @IsString 데코레이터와 : string 타입은 뭐가 다를까? (0) 2023.07.08 [ NodeJS ] Logger | .gz / gz파일 확인하기 (log.gz) (0) 2023.06.03 [ NodeJS ] 백엔드 재부팅 시 PM2 자동실행 설정 (0) 2023.05.27