forked from pankleks/pm2-health
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMail.ts
84 lines (72 loc) · 2.44 KB
/
Mail.ts
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
import * as Mailer from "nodemailer";
import * as Fs from "fs";
import { hostname } from "os";
import { info } from "./Log";
export interface ISmtpConfig {
smtp: {
host?: string;
port?: number;
user?: string;
password?: string;
secure?: boolean;
from?: string;
disabled: boolean;
},
mailTo: string;
replyTo: string;
}
export class Mail {
private _template = "<p><!-- body --></p><p><!-- timeStamp --></p>";
constructor(private _config: ISmtpConfig) {
if (!this._config.smtp)
this._config.smtp = { disabled: true };
if (this._config.smtp.disabled === true)
return; // don't analyze config if disabled
if (!this._config.smtp)
throw new Error(`[smtp] not set`);
if (!this._config.smtp.host)
throw new Error(`[smtp.host] not set`);
if (!this._config.smtp)
throw new Error(`[smtp.port] not set`);
if (!this._config.mailTo)
throw new Error(`[mailTo] not set`);
try {
this._template = Fs.readFileSync("Template.html", "utf8");
}
catch {
info(`Template.html not found`);
}
}
async send(subject: string, body: string, priority?: "high" | "low", attachements = []) {
if (this._config.smtp.disabled === true)
return;
const temp = {
host: this._config.smtp.host,
port: this._config.smtp.port,
tls: { rejectUnauthorized: false },
secure: this._config.smtp.secure === true,
auth: null
};
if (this._config.smtp.user)
temp.auth = {
user: this._config.smtp.user,
pass: this._config.smtp.password
};
const
transport = Mailer.createTransport(temp),
headers = {};
if (priority)
headers["importance"] = priority;
await transport.sendMail({
to: this._config.mailTo,
from: this._config.smtp.from || this._config.smtp.user, // use from, if not set -> user
replyTo: this._config.replyTo,
subject: `pm2-health: ${hostname()}, ${subject}`,
html: this._template
.replace(/<!--\s*body\s*-->/, body)
.replace(/<!--\s*timeStamp\s*-->/, new Date().toISOString()),
attachments: attachements,
headers
});
}
}