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

  /**
   * Send an email
   *
   * @param {string} from
   * @param {string} to
   * @param {string} replyTo
   * @param {string} subject
   * @param {string} html
   * @param {string} text
   */
Hugo SUBTIL's avatar
Hugo SUBTIL committed
  public async send(to: string | { email: string }[], subject: string, html: string): Promise<AxiosResponse<any>> {
    const emailsToSend = typeof to === 'string' ? [{ email: to }] : to;
    const formData = new FormData();
    const data = JSON.stringify({
      // eslint-disable-next-line camelcase
      from_email: this.config.from,
      // eslint-disable-next-line camelcase
      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);
          },
          (err) => {
            Logger.error(err, 'Mailer');
            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());
  }

  /**
   * 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><img src="${this.config.protocol}://${
      this.config.host
    }${
      this.config.port ? ':' + this.config.port : ''
    }/assets/logos/resin.jpg" alt="Logo resin" width="168" height="58"><br /><br /><p>Ce mail est automatique. Merci de ne pas y répondre.</p>`;
    return html;
  }