Skip to content

Commit

Permalink
✅ Verify SMTP connection configuration for transporter(s)
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexandreT-DevId committed Feb 22, 2024
1 parent 13ed63d commit ff7d8cb
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ you can find all the documentation [here](https://nest-modules.github.io/mailer/
* [Pat McGowan](https://github.com/p-mcgowan)
* [Paweł Partyka](https://github.com/partyka95)
* [Wasutan Kitijerapat](https://github.com/kitimark)
* [Alexandre Titeux](https://github.com/GFoniX)

### License

Expand Down
23 changes: 15 additions & 8 deletions lib/mailer.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/** Dependencies **/
import { get, defaultsDeep } from 'lodash';
import { Injectable, Inject, Optional } from '@nestjs/common';
import { Injectable, Inject, Optional, Logger } from '@nestjs/common';
import { SentMessageInfo, Transporter } from 'nodemailer';
import * as previewEmail from 'preview-email';
import * as smtpTransport from 'nodemailer/lib/smtp-transport';
Expand Down Expand Up @@ -46,6 +46,8 @@ export class MailerService {
}
}

private readonly mailerLogger = new Logger(MailerService.name);

constructor(
@Inject(MAILER_OPTIONS) private readonly mailerOptions: MailerOptions,
@Optional()
Expand Down Expand Up @@ -86,23 +88,28 @@ export class MailerService {
/** Transporters setup **/
if (mailerOptions.transports) {
Object.keys(mailerOptions.transports).forEach((name) => {
this.transporters.set(
name,
this.transportFactory.createTransport(
this.mailerOptions.transports![name],
),
);
this.initTemplateAdapter(this.templateAdapter, this.transporters.get(name)!);
const transporter = this.transportFactory.createTransport(this.mailerOptions.transports![name])
this.transporters.set(name, transporter);
this.verifyTransporter(transporter, name);
this.initTemplateAdapter(this.templateAdapter, transporter);
});
}

/** Transporter setup **/
if (mailerOptions.transport) {
this.transporter = this.transportFactory.createTransport();
this.verifyTransporter(this.transporter);
this.initTemplateAdapter(this.templateAdapter, this.transporter);
}
}

private verifyTransporter(transporter: Transporter, name?: string): void {
const transporterName = name ? ` '${name}'` : '';
transporter.verify()
.then(() => this.mailerLogger.error(`Transporter${transporterName} is ready`))
.catch((error) => this.mailerLogger.error(`Error occurred while verifying the transporter${transporterName}}: ${error.message}`));
}

public async sendMail(
sendMailOptions: ISendMailOptions,
): Promise<SentMessageInfo> {
Expand Down

0 comments on commit ff7d8cb

Please sign in to comment.