diff --git a/lib/Emailer.js b/lib/Emailer.js index a8841e9..9cf2087 100644 --- a/lib/Emailer.js +++ b/lib/Emailer.js @@ -1,5 +1,9 @@ 'use strict'; +// Import required modules +const nodemailer = require('nodemailer'); + +// Import user defined modules const importJSON = require('./importJSON'); /** @@ -198,6 +202,12 @@ class Emailer { */ #secure = true; + /** + * Represents the nodemailer transporter object + * @type {Object} + */ + #transporter; + /** * @param {Object} [connectionOpts] - The SMTP connection details * @param {string} connectionOpts.host - The host address of the server @@ -221,6 +231,9 @@ class Emailer { * @return {boolean} */ async sendEmail(email) { + if (typeof this.#transporter === 'undefined') + await this.getTransporter(); + console.log(`Sending`); console.log(email); console.log(this.#host, @@ -229,6 +242,37 @@ class Emailer { this.#secure); } + /** + * getTransportOptions() Builds the options object for nodemailer + * + * @return {Object} + */ + getTransportOptions() { + return { + host: this.#host, + secure: this.#secure, + auth: { + user: this.#user, + pass: this.#password + } + }; + } + + /** + * getTransporter() Gets a nodemailer transporter with current options + */ + async getTransporter() { + this.#transporter = + nodemailer.createTransport(this.getTransportOptions()); + + try { + await this.#transporter.verify(); + } catch (e) { + console.error(e); + throw new Error('Unable to connect'); + } + } + /** * Sets if the SMTP connection should be encrypted or not * @param {boolean} val - The new value @@ -238,6 +282,7 @@ class Emailer { throw new Error('Secure must be type boolean'); this.#secure = val; + this.#transporter = this.getTransporter(); } }