datasquirel/package-shared/functions/backend/handleNodemailer.ts

104 lines
2.8 KiB
TypeScript
Raw Normal View History

2025-01-10 19:10:28 +00:00
import fs from "fs";
import nodemailer, { SendMailOptions } from "nodemailer";
2024-12-06 10:31:24 +00:00
let transporter = nodemailer.createTransport({
host: process.env.DSQL_MAIL_HOST,
port: 465,
secure: true,
auth: {
user: process.env.DSQL_MAIL_EMAIL,
pass: process.env.DSQL_MAIL_PASSWORD,
},
});
2025-01-10 19:10:28 +00:00
type Param = {
to?: string;
subject?: string;
text?: string;
html?: string;
senderName?: string;
alias?: string | null;
};
2024-12-06 10:31:24 +00:00
/**
2025-01-10 19:10:28 +00:00
* # Handle mails With Nodemailer
2024-12-06 10:31:24 +00:00
*/
2025-01-10 19:10:28 +00:00
export default async function handleNodemailer({
2024-12-06 10:31:24 +00:00
to,
subject,
text,
html,
alias,
2025-01-10 19:10:28 +00:00
senderName,
}: Param): Promise<any> {
2024-12-06 10:31:24 +00:00
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (
!process.env.DSQL_MAIL_HOST ||
!process.env.DSQL_MAIL_EMAIL ||
!process.env.DSQL_MAIL_PASSWORD
) {
return null;
}
const sender = (() => {
if (alias?.match(/support/i)) return process.env.DSQL_MAIL_EMAIL;
return process.env.DSQL_MAIL_EMAIL;
})();
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
let sentMessage;
if (!fs.existsSync("./email/index.html")) {
return;
}
let mailRoot = fs.readFileSync("./email/index.html", "utf8");
let finalHtml = mailRoot
.replace(/{{email_body}}/, html ? html : "")
.replace(/{{issue_date}}/, Date().substring(0, 24));
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
try {
2025-01-10 19:10:28 +00:00
let mailObject: SendMailOptions = {};
2024-12-06 10:31:24 +00:00
2025-01-10 19:10:28 +00:00
mailObject["from"] = `"${senderName || "Datasquirel"}" <${sender}>`;
2024-12-06 10:31:24 +00:00
mailObject["sender"] = sender;
2025-01-10 19:10:28 +00:00
if (alias) mailObject["replyTo"] = sender;
2024-12-06 10:31:24 +00:00
mailObject["to"] = to;
mailObject["subject"] = subject;
mailObject["text"] = text;
mailObject["html"] = finalHtml;
// send mail with defined transport object
let info = await transporter.sendMail(mailObject);
sentMessage = info;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
2025-01-10 19:10:28 +00:00
} catch (/** @type {any} */ error: any) {
2024-12-06 10:31:24 +00:00
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
console.log("ERROR in handleNodemailer Function =>", error.message);
// serverError({
// component: "handleNodemailer",
// message: error.message,
// user: { email: to },
// });
}
return sentMessage;
2025-01-10 19:10:28 +00:00
}