@c1x/nest-mailer
Version:
A flexible and easy-to-use mailer module for NestJS applications, supporting multiple email providers including SMTP, AWS SES, and SendGrid.
123 lines • 5.64 kB
JavaScript
;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var MailerService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MailerService = void 0;
const common_1 = require("@nestjs/common");
const handlebars = require("handlebars");
const fs = require("fs");
const path = require("path");
const aws_ses_provider_1 = require("./providers/aws-ses.provider");
const sendgrid_provider_1 = require("./providers/sendgrid.provider");
const smtp_provider_1 = require("./providers/smtp.provider");
let MailerService = MailerService_1 = class MailerService {
constructor(config) {
this.config = config;
this.logger = new common_1.Logger(MailerService_1.name);
this.provider = this.initializeProvider(config);
this.templatesDir = config.templatesDir || path.join(process.cwd(), 'templates');
this.registerHandlebarsHelpers();
}
initializeProvider(config) {
try {
switch (config.provider) {
case 'aws-ses':
return new aws_ses_provider_1.AwsSesProvider(config.credentials);
case 'sendgrid':
return new sendgrid_provider_1.SendGridProvider(config.credentials);
case 'smtp':
return new smtp_provider_1.SmtpProvider(config.credentials);
default:
throw new Error(`Unsupported mail provider: ${config.provider}`);
}
}
catch (error) {
this.logger.error(`Failed to initialize mail provider: ${error.message}`);
throw error;
}
}
registerHandlebarsHelpers() {
handlebars.registerHelper('formatDate', function (date, format) {
return new Date(date).toLocaleDateString();
});
handlebars.registerHelper('formatCurrency', function (amount) {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(amount);
});
}
async compileTemplate(templateName, context) {
try {
const templatePath = path.join(this.templatesDir, `${templateName}.hbs`);
if (!fs.existsSync(templatePath)) {
throw new Error(`Template not found: ${templateName}.hbs`);
}
const templateContent = await fs.promises.readFile(templatePath, 'utf8');
const template = handlebars.compile(templateContent);
const partialsDir = path.join(this.templatesDir, 'partials');
if (fs.existsSync(partialsDir)) {
const partialFiles = fs.readdirSync(partialsDir);
for (const partialFile of partialFiles) {
if (partialFile.endsWith('.hbs')) {
const partialName = path.basename(partialFile, '.hbs');
const partialContent = fs.readFileSync(path.join(partialsDir, partialFile), 'utf8');
handlebars.registerPartial(partialName, partialContent);
}
}
}
return template(context);
}
catch (error) {
this.logger.error(`Template compilation failed: ${error.message}`);
throw error;
}
}
async sendMail(options) {
try {
let htmlContent = options.html;
if (options.template) {
this.logger.debug(`Compiling template: ${options.template}`);
htmlContent = await this.compileTemplate(options.template, options.context);
}
const mailOptions = Object.assign(Object.assign({}, options), { html: htmlContent, from: options.fromAddress });
this.validateMailOptions(mailOptions);
this.logger.debug(`Sending email to: ${mailOptions.to}`);
await this.provider.sendMail(mailOptions);
this.logger.debug('Email sent successfully');
}
catch (error) {
this.logger.error(`Failed to send email: ${error.message}`, error.stack);
throw error;
}
}
validateMailOptions(options) {
if (!options.to) {
throw new Error('Recipient (to) is required');
}
if (!options.subject) {
throw new Error('Subject is required');
}
if (!options.html && !options.text) {
throw new Error('Either html or text content is required');
}
}
};
exports.MailerService = MailerService;
exports.MailerService = MailerService = MailerService_1 = __decorate([
(0, common_1.Injectable)(),
__param(0, (0, common_1.Inject)('MAILER_CONFIG')),
__metadata("design:paramtypes", [Object])
], MailerService);
//# sourceMappingURL=mailer.service.js.map