@xfilecom/email-sender
v1.1.1
Published
Email sender module for NestJS microservices with template support
Downloads
165
Readme
@xfilecom/email-sender
Email sender module for NestJS microservices with template support
설치
npm install @xfilecom/email-sender사용법
기본 설정
import { Module } from '@nestjs/common';
import { EmailSenderModule } from '@xfilecom/email-sender';
import * as path from 'path';
@Module({
imports: [
EmailSenderModule.forRoot({
smtp: {
host: process.env.SMTP_HOST,
port: 587,
secure: false,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
},
templates: {
customPath: path.join(__dirname, 'email', 'templates'),
engine: 'handlebars',
cache: true,
watch: false, // 개발 모드에서 true로 설정
},
defaults: {
from: '[email protected]',
},
}),
],
})
export class AppModule {}환경 변수 사용
EmailSenderModule.forRoot({
smtp: {}, // 환경 변수에서 자동 읽기
templates: {
customPath: './email/templates',
},
})환경 변수:
SMTP_HOST- SMTP 호스트SMTP_PORT- SMTP 포트 (기본: 587)SMTP_SECURE- SSL/TLS 사용 여부SMTP_USER- SMTP 사용자명SMTP_PASS- SMTP 비밀번호EMAIL_FROM- 기본 발신자 이메일
이메일 발송
템플릿 사용
import { Injectable } from '@nestjs/common';
import { EmailSenderService } from '@xfilecom/email-sender';
@Injectable()
export class EmailService {
constructor(private readonly emailSender: EmailSenderService) {}
async sendWelcomeEmail(userEmail: string, userName: string) {
await this.emailSender.sendEmail({
to: userEmail,
subject: '환영합니다!',
template: 'welcome', // templates/welcome.hbs
context: {
name: userName,
email: userEmail,
},
});
}
}직접 HTML 사용
await this.emailSender.sendEmail({
to: '[email protected]',
subject: '알림',
html: '<h1>안녕하세요!</h1><p>이것은 테스트 이메일입니다.</p>',
});여러 수신자에게 발송
await this.emailSender.sendBulkEmail(
['[email protected]', '[email protected]'],
'공지사항',
'notification',
{ message: '중요한 공지사항입니다.' },
);템플릿 구조
src/
└── email/
└── templates/
├── welcome.hbs
├── password-reset.hbs
└── notification.hbs예시 템플릿 (welcome.hbs)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>환영합니다</title>
</head>
<body>
<h1>안녕하세요, {{name}}님!</h1>
<p>가입해 주셔서 감사합니다.</p>
<p>이메일: {{email}}</p>
</body>
</html>템플릿 캐시 관리
// 특정 템플릿 캐시 제거
this.emailSender.clearTemplateCache('welcome');
// 모든 템플릿 캐시 제거
this.emailSender.clearTemplateCache();API
EmailSenderService
sendEmail(options: SendEmailOptions): Promise
이메일 발송
옵션:
to: 수신자 이메일 (문자열 또는 배열)subject: 이메일 제목template: 템플릿 이름 (선택)context: 템플릿 변수 객체 (선택)html: 직접 HTML (템플릿 미사용 시)text: 텍스트 버전from: 발신자 (기본값 사용 시 생략)replyTo: 회신 주소cc: 참조bcc: 숨은 참조attachments: 첨부 파일 배열
sendBulkEmail(recipients, subject, template?, context?, html?): Promise<SendEmailResult[]>
여러 수신자에게 동일한 이메일 발송
verifyConnection(): Promise
SMTP 연결 확인
템플릿 엔진
현재 지원: Handlebars
향후 지원 예정: EJS, Mustache
인증 코드 기능 (Verification Code)
설정
인증 코드 기능을 사용하려면 RedisManagerModule이 필요합니다:
import { Module } from '@nestjs/common';
import { CoreModule } from '@xfilecom/core-sdk';
import { RedisManagerModule, RedisManagerService } from '@xfilecom/redis-manager';
import { EmailSenderModule, VerificationCodeService } from '@xfilecom/email-sender';
@Module({
imports: [
CoreModule.forRoot({ serviceType: 'hybrid' }),
RedisManagerModule.forRoot({
keyPrefix: 'myapp:',
}),
EmailSenderModule.forRoot({
smtp: {},
templates: {
customPath: './email/templates',
},
verificationCode: {
codeLength: 6,
expiresIn: 600, // 10분
maxAttempts: 5,
resendCooldown: 60, // 1분
dailyLimit: 10,
keyPrefix: 'verification:',
},
}),
],
})
export class AppModule {
constructor(
private readonly verificationCode: VerificationCodeService,
private readonly redisManager: RedisManagerService,
) {
// RedisManager 설정 (필수)
this.verificationCode.setRedisManager(this.redisManager);
}
}사용 예시
import { Injectable } from '@nestjs/common';
import { VerificationCodeService } from '@xfilecom/email-sender';
@Injectable()
export class AuthService {
constructor(private readonly verificationCode: VerificationCodeService) {}
async sendVerificationCode(email: string) {
return await this.verificationCode.sendCode(email, 'verification', true);
}
async verifyCode(email: string, code: string) {
return await this.verificationCode.verifyCode(email, code, 'verification');
}
}인증 코드 템플릿
email/templates/verification-code.hbs 파일 생성:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>인증 코드</title>
</head>
<body>
<h1>인증 코드</h1>
<p>{{purpose}}을 위한 인증 코드입니다:</p>
<h2 style="font-size: 32px; letter-spacing: 8px; color: #007bff;">{{code}}</h2>
<p>이 코드는 {{expiresIn}}분 후에 만료됩니다.</p>
</body>
</html>라이선스
MIT
