|
| 1 | +import * as dotenv from 'dotenv'; |
| 2 | +import * as nodemailer from 'nodemailer'; |
| 3 | + |
| 4 | +import { EmailDto } from './dtos/email.dto'; |
| 5 | +import { Logger } from '@nestjs/common'; |
| 6 | + |
| 7 | +dotenv.config(); |
| 8 | + |
| 9 | +const emailProvider = process.env.EMAIL_PROVIDER?.toLowerCase(); |
| 10 | + |
| 11 | +let transporter: nodemailer.Transporter | null = null; |
| 12 | + |
| 13 | +if ('smtp' === emailProvider) { |
| 14 | + const { SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS } = process.env; |
| 15 | + |
| 16 | + if (!SMTP_HOST || !SMTP_PORT || !SMTP_USER || !SMTP_PASS) { |
| 17 | + throw new Error('Missing SMTP configuration. Required: SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS'); |
| 18 | + } |
| 19 | + |
| 20 | + const port = Number(SMTP_PORT); |
| 21 | + |
| 22 | + if (!Number.isInteger(port) || 0 >= port) { |
| 23 | + throw new Error(`Invalid SMTP_PORT value: "${SMTP_PORT}". Must be a valid number.`); |
| 24 | + } |
| 25 | + |
| 26 | + transporter = nodemailer.createTransport({ |
| 27 | + host: SMTP_HOST, |
| 28 | + port: Number(SMTP_PORT), |
| 29 | + secure: 465 === Number(SMTP_PORT), |
| 30 | + auth: { |
| 31 | + user: SMTP_USER, |
| 32 | + pass: SMTP_PASS |
| 33 | + }, |
| 34 | + requireTLS: 587 === Number(SMTP_PORT) |
| 35 | + }); |
| 36 | +} |
| 37 | + |
| 38 | +export const sendWithSMTP = async (emailDto: EmailDto): Promise<boolean> => { |
| 39 | + if (!transporter) { |
| 40 | + Logger.error('SMTP email provider is not initialized'); |
| 41 | + return false; |
| 42 | + } |
| 43 | + |
| 44 | + try { |
| 45 | + await transporter.sendMail({ |
| 46 | + from: emailDto.emailFrom, |
| 47 | + to: emailDto.emailTo, |
| 48 | + subject: emailDto.emailSubject, |
| 49 | + text: emailDto.emailText, |
| 50 | + html: emailDto.emailHtml, |
| 51 | + attachments: emailDto.emailAttachments |
| 52 | + }); |
| 53 | + |
| 54 | + return true; |
| 55 | + } catch (error) { |
| 56 | + Logger.error('Error while sending email with SMTP', error); |
| 57 | + return false; |
| 58 | + } |
| 59 | +}; |
0 commit comments