Skip to content
Snippets Groups Projects
mailer.service.ts 2.77 KiB
Newer Older
  • Learn to ignore specific revisions
  • 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
       */
    
      public async send(to: string, subject: string, html: string): Promise<AxiosResponse<any>> {
        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,
    
          reply_to: 'inclusionnumerique@grandlyon.com',
    
          subject: subject,
          content: 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 : ${subject} success`, '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());
      }
    }