first commit
This commit is contained in:
9
src/mail/mail.module.ts
Normal file
9
src/mail/mail.module.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { MailService } from './mail.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [MailService],
|
||||
exports: [MailService],
|
||||
})
|
||||
export class MailModule {}
|
||||
44
src/mail/mail.service.ts
Normal file
44
src/mail/mail.service.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import * as nodemailer from 'nodemailer';
|
||||
import { PinoLogger } from 'nestjs-pino';
|
||||
|
||||
@Injectable()
|
||||
export class MailService {
|
||||
private transporter: nodemailer.Transporter;
|
||||
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly logger: PinoLogger,
|
||||
) {
|
||||
this.logger.setContext(MailService.name);
|
||||
this.transporter = nodemailer.createTransport({
|
||||
host: this.configService.get<string>('SMTP_HOST'),
|
||||
port: this.configService.get<number>('SMTP_PORT'),
|
||||
secure: false,
|
||||
auth: this.configService.get<string>('SMTP_USER')
|
||||
? {
|
||||
user: this.configService.get<string>('SMTP_USER'),
|
||||
pass: this.configService.get<string>('SMTP_PASSWORD'),
|
||||
}
|
||||
: undefined,
|
||||
tls: { rejectUnauthorized: false },
|
||||
});
|
||||
}
|
||||
|
||||
async sendCode(to: string, code: string, purpose: string): Promise<void> {
|
||||
const from = this.configService.get<string>('SMTP_FROM')!;
|
||||
try {
|
||||
await this.transporter.sendMail({
|
||||
from,
|
||||
to,
|
||||
subject: `SSO: код ${purpose === 'AUTH' ? 'для входа' : 'подтверждения'}`,
|
||||
text: `Ваш код: ${code}\nДействителен 5 минут.`,
|
||||
html: `<p>Ваш код: <strong>${code}</strong></p><p>Действителен 5 минут.</p>`,
|
||||
});
|
||||
this.logger.info({ to, purpose }, 'Verification code sent via email');
|
||||
} catch (err: unknown) {
|
||||
this.logger.error({ err: err as Error, to }, 'Failed to send email');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user