Newer
Older
import { HttpService } from '@nestjs/axios';
import { Injectable, Logger } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';
import { ConfigurationService } from '../configuration/configuration.service';
@Injectable()
export class MailerService {
public config = null;
constructor(private readonly httpService: HttpService, private configurationService: ConfigurationService) {
this.config = this.configurationService.config;
}
public async send(to: string | { email: string }[], subject: string, html: string): Promise<AxiosResponse<unknown>> {
const emailsToSend = typeof to === 'string' ? [{ email: to }] : to;
const formData = new FormData();
const data = JSON.stringify({
from_email: this.config.from,
from_name: this.config.from_name,
reply_to: 'inclusionnumerique@grandlyon.com',
subject: subject,
content: this.addSignature(html),
});
formData.append('metadata', data);
const contentLength = formData.getLengthSync();
Logger.log(`Send mail : ${subject}`, 'Mailer');
return new Promise((resolve, reject) => {
this.httpService
.post(process.env.MAIL_URL, formData, {
'Content-Length': contentLength,
Authorization: 'Bearer ' + process.env.MAIL_TOKEN,
...formData.getHeaders(),
},
})
.subscribe(
(body) => {
Logger.log(`Send mail - success : ${subject}`, 'Mailer');
return resolve(body);
},
(err) => {
Logger.error(err, 'Mailer');
return reject(err);
}
);
});
}
/**
* Get email template location from config directory and given filename. Also, check if file exists.
*/
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
*/
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());
}
/**
* Add site mail signature to a given html
* @param html
*/
public addSignature(html: string): string {
html += `<br /><br /><p>L’équipe projet inclusion numérique.</p><p style="font-family:helvetica;font-size:24px;font-weight:bold;margin:0;">rés<span style="color:red;font-weight:400;">’in</span></p><br /><br /><p>Ce mail est automatique. Merci de ne pas y répondre.</p>`;