Newer
Older
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
import { HttpService, Injectable, Logger } from '@nestjs/common';
import { ConfigurationService } from '../configuration/configuration.service';
import * as fs from 'fs';
import * as path from 'path';
@Injectable()
export class MailerService {
public config = null;
constructor(private readonly httpService: HttpService, private configurationService: ConfigurationService) {
this.config = this.configurationService.config;
}
/**
* Send an email
*
* @param {string} from
* @param {string} to
* @param {string} replyTo
* @param {string} subject
* @param {string} html
* @param {string} text
*/
public send(to: string, subject: string, html: string): Promise<any> {
const data = JSON.stringify({
from: this.config.from,
// eslint-disable-next-line camelcase
from_name: this.config.from_name,
to: to,
subject: subject,
content: html,
});
Logger.log(`[Mailer] Send mail : ${subject}`);
return new Promise((resolve, reject) => {
this.httpService
.post(process.env.MAIL_URL, data, {
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + process.env.MAIL_TOKEN,
},
})
.subscribe(
(body) => {
Logger.log(`[Mailer] Send mail : ${subject} success`);
return resolve(body);
},
(err) => {
Logger.error(err);
return reject(err);
}
);
});
}
/**
* Get email template location from config directory and given filename. Also, check if file exists.
*
* @param {string} filename
*/
public getTemplateLocation(filename) {
const ejsPath = path.join(this.config.templates.directory, filename);
if (!fs.existsSync(ejsPath)) {
throw new Error(`Email template '${filename}' cannot be found in ${this.config.templates.directory}`);
}
return ejsPath;
}
/**
* Load email json config file from config directory and given filename. Also, check if file exists
*
* @param {filename} filename
*/
public loadJsonConfig(filename) {
const jsonPath = path.join(this.config.templates.directory, filename);
if (!fs.existsSync(jsonPath)) {
throw new Error(`Email json definition file '${filename}' cannot be found in ${this.config.templates.directory}`);
}
return JSON.parse(fs.readFileSync(jsonPath).toString());
}
}