-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemail.js
More file actions
100 lines (88 loc) · 3.05 KB
/
Copy pathemail.js
File metadata and controls
100 lines (88 loc) · 3.05 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import nodemailer from 'nodemailer';
import pug from 'pug';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import path from 'path';
import { convert } from 'html-to-text';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// new Email(user, url).sendWelcome();
export default class Email {
constructor(user, url) {
this.to = user.email,
this.firstName = user.name.split(' ')[0],
this.url = url,
this.from = process.env.MAIL_FROM_ADDRESS
}
newCreateTransport() {
if (process.env.NODE_ENV.trim() === "production") {
// SENDGRID
return nodemailer.createTransport({
service: 'SendGrid', // we don't need to pass host and port if we use service
auth: {
user: process.env.SENDGRID_USERNAME,
pass: process.env.SENDGRID_PASSWORD,
}
});
return 1;
}
// 1) Create a transporter
return nodemailer.createTransport({
host: process.env.MAIL_HOST,
port: process.env.MAIL_PORT,
auth: {
user: process.env.MAIL_USERNAME,
pass: process.env.MAIL_PASSWORD,
}
// Activate in gmail "less secure app" option
});
}
// Send the actual template
async send(template, subject){
// 1) Render HTML based on a pug template
// res.render('');
const html = pug.renderFile(path.join(__dirname, `./../views/emails/${template}.pug`), {
firstName: this.firstName,
subject,
url: this.url
});
// 2) Define email options
const emailOptions = {
from: this.from,
to: this.to,
subject,
html,
text: convert(html)
}
// 3) create a transport and send email
await this.newCreateTransport().sendMail(emailOptions);
}
async sendWelcome() {
await this.send("welcome", "Welcome to the Natours Family!");
}
async sendPasswordReset() {
await this.send("passwordReset", "Your reset password token (valid for only 10 minutes)");
}
}
// export const sendEmail = async options => {
// // 1) Create a transporter
// const transporter = nodemailer.createTransport({
// host: process.env.MAIL_HOST,
// port: process.env.MAIL_PORT,
// auth: {
// user: process.env.MAIL_USERNAME,
// pass: process.env.MAIL_PASSWORD,
// }
// // Activate in gmail "less secure app" option
// });
// // 2) Define the email options
// const emailOptions = {
// from: process.env.MAIL_FROM_ADDRESS,
// to: options.email,
// subject: options.subject,
// text: options.message
// // html
// }
// // 3) Actually send the email
// await transporter.sendMail(emailOptions);
// }