import { Global, Injectable, Logger, Module } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { createTransport, Transporter } from 'nodemailer'; /** * Envoi d'e-mails transactionnels. Sans SMTP configuré (développement), * le message est écrit dans les logs au lieu d'être envoyé. */ @Injectable() export class MailService { private readonly logger = new Logger(MailService.name); private readonly transport: Transporter | null; private readonly from: string; constructor(config: ConfigService) { const mail = config.get('mail'); this.from = mail.from; this.transport = mail.host ? createTransport({ host: mail.host, port: mail.port, secure: mail.port === 465, auth: mail.user ? { user: mail.user, pass: mail.pass } : undefined, }) : null; } async send(to: string, subject: string, text: string, html: string, replyTo?: string) { if (!this.transport) { this.logger.warn(`SMTP non configuré — e-mail à ${to} : « ${subject} »\n${text}`); return; } await this.transport.sendMail({ from: this.from, to, subject, text, html, ...(replyTo && { replyTo }) }); } } @Global() @Module({ providers: [MailService], exports: [MailService] }) export class MailModule {}