import { Transporter, createTransport, TransportOptions } from "nodemailer"; import { Attachment } from "nodemailer/lib/mailer"; import SettingHelper from "./settingsHelper"; import emailCheck from "email-check"; export default abstract class MailHelper { private static transporter: Transporter; static createTransport() { this.transporter?.close(); this.transporter = createTransport({ host: SettingHelper.getSetting("mail.host"), port: SettingHelper.getSetting("mail.port"), secure: SettingHelper.getSetting("mail.secure"), auth: { user: SettingHelper.getSetting("mail.username"), pass: SettingHelper.getSetting("mail.password"), }, } as TransportOptions); } static async verifyTransport({ host, port, secure, user, password, }: { host: string; port: number; secure: boolean; user: string; password: string; }): Promise { let transport = createTransport({ host, port, secure, auth: { user, pass: password }, }); return await transport .verify() .then(() => { return true; }) .catch(() => { return false; }) .finally(() => { try { transport?.close(); } catch (error) {} }); } static async checkMail(mail: string): Promise { return await emailCheck(mail) .then((res) => { return res; }) .catch((err) => { return false; }); } static initialize() { SettingHelper.onSettingTopicChanged("mail", () => { this.createTransport(); }); this.createTransport(); } /** * @description send mail * @param {string} target * @param {string} subject * @param {string} content * @returns {Prmose<*>} */ static async sendMail( target: string, subject: string, content: string, attach: Array = [] ): Promise { return new Promise((resolve, reject) => { this.transporter .sendMail({ from: `"${SettingHelper.getSetting("club.name")}" <${SettingHelper.getSetting("mail.email")}>`, to: target, subject, text: content, html: content, attachments: attach, }) .then((info) => resolve(info.messageId)) .catch((e) => reject(e)); }); } }