forked from yigitocak/Pixel-Punch-Out-Server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
emailSender.js
71 lines (61 loc) · 1.71 KB
/
emailSender.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import "dotenv/config";
import nodemailer from "nodemailer";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
// Fix for ES modules: __dirname replacement
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const EMAIL = process.env.EMAIL;
const EMAIL_PASSWORD = process.env.EMAIL_PASSWORD;
const FRONTEND_URL = process.env.FRONTEND_URL;
const generateCode = () => {
return Math.floor(100000 + Math.random() * 900000);
};
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: EMAIL,
pass: EMAIL_PASSWORD,
},
});
export const sendEmail = (mailTo, subject, mode) => {
const code = generateCode();
const filePath =
mode === 1
? path.join(__dirname, "email.html")
: path.join(__dirname, "forgot_email.html");
// Read the HTML template
fs.readFile(filePath, { encoding: "utf-8" }, (err, html) => {
if (err) {
console.error("Error reading HTML file:", err);
return;
}
let htmlWithCode;
if (mode === 1) {
htmlWithCode = html.replace("{{verification_code}}", code.toString());
} else {
const email = encodeURIComponent(mailTo); // Ensure the email is URL-encoded
htmlWithCode = html.replace(
"{{link}}",
`${FRONTEND_URL}reset?email=${email}&code=${code}`,
);
}
const mailOptions = {
from: EMAIL,
to: mailTo,
subject: subject,
html: htmlWithCode,
};
// Send the email
const send = async () => {
try {
const info = await transporter.sendMail(mailOptions);
} catch (err) {
console.error("Error sending email:", err);
}
};
send();
});
return code;
};