File

src/service/1.0.0/email.service.ts

Index

Properties
Methods

Methods

Private initializeTransport
initializeTransport()
Returns : void
Async sendEmail
sendEmail(templateName: string, to: string[], subject: string, vars: object, attachments: any[])
Parameters :
Name Type Optional Default value
templateName string No
to string[] No
subject string No
vars object No
attachments any[] No []
Returns : Promise<void>

Properties

Private transport
Type : Mail
Default value : undefined
import { Injectable } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';
import { createTransport, TransportOptions } from 'nodemailer';
import Mail = require('nodemailer/lib/mailer');
import { Config } from 'src/module/config/entity/config';
import stripHtml from 'string-strip-html';



@Injectable()
export class EmailService {

	private transport: Mail = undefined;

	async sendEmail(templateName: string, to: string[], subject: string, vars: object, attachments: any[] = []): Promise<void> {

		if (this.transport === undefined) {

			this.initializeTransport();

		}

		let template = fs.readFileSync(path.resolve(__dirname, `../../../template/email/${templateName}.html`)).toString()
		for (const key of Object.keys(vars)) {

			template = template.replace(new RegExp(`{{ ${key} }}`, `g`), vars[key]);

		}

		await this.transport.sendMail({

			to: to.join(','),
			from: Config.get('SMTP_EMAIL'),
			subject,
			html: template,
			text: stripHtml(template),
			attachments: attachments
		});

	}

	private initializeTransport(): void {

		this.transport = createTransport({

			host: Config.get('SMTP_HOST') as string,
			port: parseInt(Config.get('SMTP_PORT'), 10),
			secure: Config.get('SMTP_SECURE') === 'true',
			auth: {

				user: Config.get('SMTP_USER') as string,
				pass: Config.get('SMTP_PASSWORD') as string

			}

		} as TransportOptions);

	}

}

result-matching ""

    No results matching ""