import { ConflictException, Inject, Injectable } from '@nestjs/common' import { securityConfig, SecurityConfig } from 'src/common/configs' import { MailerService } from '@nestjs-modules/mailer' import { JwtService } from '@nestjs/jwt' import { EmailScene } from './dto/email.dto' import { PrismaService } from 'nestjs-prisma' @Injectable() export class EmailService { constructor( private prismaService: PrismaService, private mailerService: MailerService, private jwtService: JwtService, @Inject(securityConfig.KEY) private secureConfig: SecurityConfig, ) {} async sendEmailTo(email: string) { return this.mailerService.sendMail({ to: email, // list of receivers subject: 'Testing Nest Mailermodule with template ✔', template: 'index', // The `.pug` or `.hbs` extension is appended automatically. context: { // Data to be sent to template engine. code: 'cf1a3f828287', username: 'john doe', }, }) } async getRegisterToken(email: string, scene: EmailScene) { const user = await this.prismaService.user.findUnique({ where: { email } }) if (user) { throw new ConflictException(`邮箱${email}已注册`) } const verificationCode = this.generateRandomNum() const registerToken = this.jwtService.sign( { email, scene }, { secret: this.secureConfig.jwt_access_secret + verificationCode + scene, expiresIn: '30min', }, ) await this.mailerService.sendMail({ to: email, subject: '注册qiuxu.site', html: `您正在注册qiuxu.site,验证码为 ${verificationCode},30分钟内有效`, }) return { registerToken, verificationCode } } private generateRandomNum() { return Math.floor(Math.random() * 899999 + 100000) } }