-
Notifications
You must be signed in to change notification settings - Fork 14
/
Mail.ts
101 lines (87 loc) · 2.9 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import * as Mailer from "nodemailer";
import * as Fs from "fs";
import { hostname } from "os";
import { info, debug, error } from "./Log";
export interface ISmtpConfig {
smtp: {
host?: string;
port?: number;
user?: string;
password?: string;
secure?: boolean;
from?: string;
disabled: boolean;
clientHostName?: string;
},
mailTo: string;
replyTo: string;
batchPeriodM?: number;
batchMaxMessages?: number;
}
export interface IMessage {
subject: string;
body: string;
priority?: "high" | "low";
attachements?: any[];
on?: Date
}
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`);
try {
this._template = Fs.readFileSync("Template.html", "utf8");
}
catch {
info(`Template.html not found`);
}
}
configChanged() {
if (!this._config.mailTo)
throw new Error(`[mailTo] not set`);
}
async send(message: IMessage) {
if (this._config.smtp.disabled === true) {
debug("mail sending is disbled in config");
return;
}
const temp = {
host: this._config.smtp.host,
port: this._config.smtp.port,
tls: { rejectUnauthorized: false },
secure: this._config.smtp.secure === true,
auth: null,
name: typeof this._config.smtp.clientHostName == "string" && this._config.smtp.clientHostName ? this._config.smtp.clientHostName : 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 (message.priority)
headers["importance"] = message.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()}, ${message.subject}`,
html: this._template
.replace(/<!--\s*body\s*-->/, message.body)
.replace(/<!--\s*timeStamp\s*-->/, new Date().toISOString()),
attachments: message.attachements,
headers
});
}
}