Skip to content
Snippets Groups Projects
email.service.ts 1.38 KiB
Newer Older
  • Learn to ignore specific revisions
  • ncastejon's avatar
    ncastejon committed
    import { Injectable, Logger } from '@nestjs/common';
    
    import * as amqp from 'amqplib/callback_api';
    
    import { ContactForm, Email } from './email';
    
    
    @Injectable()
    export class EmailService {
    
    
      send(contactForm: ContactForm): boolean {
    
        const rabbitmqUrl = 'amqp://user:password123@rabbitmq:5672';
    
        const mailerQueue = 'portail-data-send-email';
    
    
        const email = new Email();
        email.from = `${contactForm.firstname} ${contactForm.lastname} ${contactForm.from}`;
    
        email.to = [process.env.ADMIN_EMAIL];
    
        email.subject = contactForm.subject;
        email.text = contactForm.text;
    
        Logger.log(email);
    
    
        // Connect to rabbitmq
    
        return amqp.connect(rabbitmqUrl, (err, conn) => {
          if (err != null) {
            Logger.log(err);
            return false;
          } else {
            // Create a communication channel
    
    FORESTIER Fabien's avatar
    FORESTIER Fabien committed
            return conn.createChannel((error, ch) => {
    
              if (error != null) {
                Logger.log(error);
                return false;
              } else {
                // Stringify and bufferise message
                const buffer = Buffer.from(JSON.stringify(email));
    
                ch.assertQueue(mailerQueue, { durable: true });
    
                ch.sendToQueue(mailerQueue, buffer, { persistent: true });
    
                Logger.log(`sent to queue ${mailerQueue}: ${JSON.stringify(email)}`);
    
                conn.close();
    
                return true;
              }
            });
          }