Skip to content
Snippets Groups Projects
mailer.service.ts 3.01 KiB
Newer Older
import { HttpService } from '@nestjs/axios';
import { Injectable, Logger } from '@nestjs/common';
import { AxiosResponse } from 'axios';
Bastien DUMONT's avatar
Bastien DUMONT committed
import * as FormData from 'form-data';
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;
  }

Bastien DUMONT's avatar
Bastien DUMONT committed
  public async send(to: string | { email: string }[], subject: string, html: string): Promise<AxiosResponse<unknown>> {
Hugo SUBTIL's avatar
Hugo SUBTIL committed
    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,
Antonin COQUET's avatar
Antonin COQUET committed
      to: emailsToSend,
      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,
          },
        })
        .subscribe(
          (body) => {
            Logger.log(`Send mail - success : ${subject}`, 'Mailer');
            return resolve(body.data);
            Logger.error(err, 'Mailer');
            return reject(err);
          }
        );
    });
  }

  /**
   * Get email template location from config directory and given filename. Also, check if file exists.
   */
Bastien DUMONT's avatar
Bastien DUMONT committed
  public getTemplateLocation(filename: string) {
    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
   */
Bastien DUMONT's avatar
Bastien DUMONT committed
  public loadJsonConfig(filename: string) {
    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>`;
    return html;
  }