ff-admin-server/src/helpers/mailHelper.ts

102 lines
2.3 KiB
TypeScript

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<boolean> {
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<boolean> {
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<Attachment> = []
): Promise<any> {
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));
});
}
}