@chelseaapps/notification documentation

import { Process, Processor } from '@nestjs/bull';
import { Inject, Logger } from '@nestjs/common';
import { Job } from 'bull';
import * as NodeMailer from 'nodemailer';
import { NOTIFICATION_OPTIONS } from '../constants';
import { NotificationOptions } from '../interfaces';
import { IEmailPayload } from './email.interface';

@Processor('email')
export class EmailConsumer {
    private readonly logger = new Logger(EmailConsumer.name);

    private client: NodeMailer.Transporter;

    constructor(@Inject(NOTIFICATION_OPTIONS) private options: NotificationOptions) {
        this.client = NodeMailer.createTransport({
            host: options.email.host,
            port: options.email.port,
            secure: +options.email.port === 465,
            auth: {
                user: options.email.user,
                pass: options.email.password,
            },
        });
    }

    /**
     * Send an email to a set of addresses
     * @param to List of email addresses
     * @param from Email from field. Default provided
     * @param subject Email subject
     * @param body Email HTML body
     */
    @Process()
    async send({ data: { to, subject, body, from } }: Job<IEmailPayload>): Promise<void> {
        if (process.env.NODE_ENV === 'test') return null;

        let response: any = null;
        try {
            response = await this.client.sendMail({
                from,
                to,
                subject,
                html: body,
            });
            this.logger.verbose(`Email delivered [${subject}, ${to}]`);
        } catch (err) {
            // Failed to send email
            this.logger.error('Failed to send email', err);
        }
        return response;
    }
}

Was this helpful?