summaryrefslogtreecommitdiff
path: root/src/lib/utils/mailer.ts
blob: e5edd74a6b67ce4749599673a53d1dadb2205cd7 (plain)
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
import * as nodemailer from 'nodemailer';
import { continueRetryUntilValidation } from './retry';

export interface Mailer {
	sendMail(to: string, subject: string, message: string): Promise<boolean>;
}

export class MistyMountainsMailer implements Mailer {
	private from: string;
	private domain: string;
	private username: string;
	private password: string;
	private port: number;

	private transporter: nodemailer.Transporter;

	constructor(username: string, password: string, from: string, domain: string, port: number) {
		this.from = from;
		this.username = username;
		this.password = password;
		this.domain = domain;
		this.port = port;

		this.transporter = nodemailer.createTransport({
			host: this.domain,
			port: this.port,
			auth: {
				user: this.username,
				pass: this.password
			},
			requireTLS: true,
			tls: {
				rejectUnauthorized: true
			}
		});
	}

	public async sendMail(to: string, subject: string, message: string) {
		const mail = {
			from: this.from,
			subject,
			html: message,
			to
		};

		return !!(await continueRetryUntilValidation<string>(async () => {
			const { messageId } = await this.transporter.sendMail(mail);
			return messageId;
		}));
	}
}

export const EnvMistyMountainsMailerFactory = () => {
	return new MistyMountainsMailer(
		process.env.SMTP_USERNAME,
		process.env.SMTP_PASSWORD,
		process.env.FROM_EMAIL,
		process.env.SMTP_SERVER,
		Number(process.env.SMTP_PORT)
	);
};