/* eslint-disable @typescript-eslint/no-base-to-string */ /* eslint-disable no-console */ import { globalServices } from "../../../globalServices.js"; import DnsService from "../dns/DnsService.js"; import TimeoutError from "../../../common/errors/TimeoutError.js"; import { SmtpStatusCodes } from "./SmtpStatusCodes.js"; import SimpleLogger from "../../../common/SimpleLogger.js"; import ESmtpClient from "../../../protocols/smtp/ESmtpClient.js"; import SmtpError from "../services/SmtpError.js"; import { LocalFile } from "@entity-access/server-pages/dist/core/LocalFile.js"; import ServerLogger from "@entity-access/server-pages/dist/core/ServerLogger.js"; import { NODATA, NOTFOUND } from "node:dns"; export interface ISmtpClientEnvelope { host: string; from: string; to: string[]; // appFileID: number; } export interface ISmtpResponse { status: string; statusCode: SmtpStatusCodes; logs: string } export default class SMTPClient { private client: ESmtpClient; private logger: SimpleLogger = new SimpleLogger(); private sent = false; constructor( private config: { helo?: string, host: string, port?: number } ) { } async connect() { const dns = globalServices.resolve(DnsService); const mx = await dns.getMXAddresses(this.config.host); const logs = []; const timer = setTimeout(() => console.log(JSON.stringify({ action: "esmtp-connect", host: this.config.host, logs, timeout: 30 })), 30000); for (const { host, ip } of mx) { try { this.client = await ESmtpClient.connect({ ... this.config, host: ip, servername: host, logger: (data) => { logs.push(data); // console.log(data); this.logger?.info(data); } }); clearTimeout(timer); return this; } catch (error) { if (error.code === "ECONNREFUSED" || error.code === NOTFOUND || error.code === NODATA || /timeout/i.test(error?.stack ?? error) ) { throw error; } console.error(error); } } throw new TimeoutError(`Could not connect any known mx hosts for ${this.config.host}`); } async send(envelope: ISmtpClientEnvelope, file: LocalFile): Promise { using _a = this.logger.newScope(); if (this.sent) { try { await this.client.reset(); } catch (error) { ServerLogger.error({ error }); this.client.dispose(); await this.connect(); } } this.sent = true; try { await this.client.send(envelope.from, envelope.to, file); return { logs: this.logger.logs, status: "250", statusCode: 250 }; } catch (error) { if (error instanceof SmtpError) { return { logs: this.logger.logs, status: error.responseCode.toString(), statusCode: error.responseCode }; } console.error(error); return { logs: this.logger.logs, status: error.stack ?? error.toString(), statusCode: SmtpStatusCodes.TransactionFailed }; } } onEnd(fx) { this.client.eventClosed.listen(fx); } async dispose() { this.client[Symbol.dispose](); } }