-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemail.js
More file actions
69 lines (46 loc) · 1.44 KB
/
email.js
File metadata and controls
69 lines (46 loc) · 1.44 KB
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
// mailer.js
const nodemailer = require('nodemailer');
const fs = require('fs');
const path = require('path');
require('dotenv').config();
// Reusable transporter using Gmail
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.GMAIL_USER,
pass: process.env.GMAIL_PASS
}
});
const sendEmail = async (to, subject, templateName, variables = {}) => {
if (!to || typeof to !== 'string') {
console.error('No valid recipient email address provided.');
return;
};
const templatePath = path.join(__dirname, 'templates', templateName);
let html = fs.readFileSync(templatePath, 'utf-8');
// Replace {{placeholders}} with actual values
for (const key in variables) {
const pattern = new RegExp(`{{\\s*${key}\\s*}}`, 'g');
html = html.replace(pattern, variables[key]);
}
const mailOptions = {
from: `"Test App" <${process.env.GMAIL_USER}>`,
to,
subject,
html
};
// return transporter.sendMail(mailOptions, (error, info) => {
// if (error) {
// return console.error('Error while sending email:', error);
// }
// console.log('Email sent:', info.messageId);
// console.log('Email receiver:', mailOptions.to);
// });
try {
const info = await transporter.sendMail(mailOptions);
console.log('Email sent:', info.messageId);
} catch (error) {
console.error('Error while sending email:', error.message);
}
};
module.exports = sendEmail;