Source: plugins/outbound/email/base.js

const EventEmitter = require('events');
const nodemailer = require('nodemailer');
const Basedata = require('../../../models/basedata');

class sendemail extends EventEmitter {
    constructor() {
        super();
        global.plgManager.logger.info('-------- PLUGIN SENDEMAIL -----------');
        //this.plgManager = global.plgManager;
        this.registerForEvents();
        this.serviceProcId = null;
        this.loadConfig((success) => {
            if (success) {
                global.plgManager.logger.info('PLUGIN | SENDMAIL | successfully loaded Configuration from core database');
                this.initializePlugin((successInit) => {
                    if (successInit) {
                        global.plgManager.logger.info('PLUGIN | SENDMAIL | successfully initialized plugin. Ready to send eMails now.');
                    } else {
                        global.plgManager.logger.error('PLUGIN | SENDMAIL | something went wrong initializing plugin');
                    }
                });
            } else {
                global.plgManager.logger.error('PLUGIN | SENDMAIL | something went wrong loading configuration. Can not send eMails!!');
            }
        });
        this.transporter = null;
    }

    /**
     * Registration of Events at the plugin manager (hook in to events provided by the plugin manager)
     */
    registerForEvents() {
        global.plgManager.logger.info('PLUGIN | SENDEMAIL | Registering events')
        global.plgManager.on('event_send_email', (emailInfo) => {
            global.plgManager.logger.info('PLUGIN | SENDEMAIL | EVENT event_send_email recieved');
            this.initializePlugin((success) => {
                if (success) {
                    this.to = emailInfo.to;
                    this.subject = emailInfo.subject;
                    this.plaintext = emailInfo.plaintext;
                    this.htmltext = emailInfo.htmltext;
                    this.setupTransporter();
                    this.setupMail();
                    this.sendMail();
                }    
            });
        });
        global.plgManager.on('event_new_alarm', (alarmInfo) => {
            global.plgManager.logger.info('PLUGIN | SENDEMAIL | EVENT event_new_alarm recieved');
            this.initializePlugin((success) => {
                if (success) {
                    this.to = 'jens.dinstuehler@feuerwehr-reichenschwand.de';
                    this.subject = this.subject + ' ALARM - ' + alarmInfo.subject.value;
                    this.plaintext = 'Mitteilung:\n' + alarmInfo.message.value + '\n\nOrt: ' + alarmInfo.location.value + '\n\nEinsatzmittel: ' + alarmInfo.gear.value;
                    this.htmltext = '';
                    this.setupTransporter();
                    this.setupMail();
                    this.sendMail();
                }
            });
        })
        global.plgManager.on('event_new_test_alarm', (basedataId, pluginNamespace, alarmInfo) => {
            if (pluginNamespace === 'sendemail') {
                global.plgManager.logger.info('PLUGIN | SENDEMAIL | EVENT event_new_test_alarm recieved -> processing now');
                // get eMail-Adress
                var basedata = new Basedata(global.logger);
                basedata.getBaseDataForId(basedataId, (rowsBasedata) => {
                    if (rowsBasedata !== null) {
                        if (rowsBasedata.length > 0 ) {
                            var recipientaddress = rowsBasedata[0].email;
                            if (recipientaddress.length > 0 ) {
                                this.initializePlugin((success) => {
                                    if (success) {
                                        console.log('sending to: ' + recipientaddress);
                                        this.to = recipientaddress;
                                        this.subject = this.subject + ' ALARM - ' + alarmInfo.subject.value;
                                        this.plaintext = 'Mitteilung:\n' + alarmInfo.message.value + '\n\nOrt: ' + alarmInfo.location.value + '\n\nEinsatzmittel: ' + alarmInfo.gear.value;
                                        this.htmltext = '';
                                        this.setupTransporter();
                                        this.setupMail();
                                        this.sendMail();
                                    }
                                });
                            } else {
                                // Member has no email-address set
                            
                                global.plgManager.logger.info('PLUGIN | SENDEMAIL | EVENT event_new_test_alarm recieved -> Member does not have an eMail address set');
                            }
                        } else {
                            // No basedata entry found
                            global.plgManager.logger.info('PLUGIN | SENDEMAIL | EVENT event_new_test_alarm recieved -> Could not find Basedata entry for member');
                        }
                    } else {
                        // Error getting basedata from core database
                        global.plgManager.logger.info('PLUGIN | SENDEMAIL | EVENT event_new_test_alarm recieved -> Could not find Basedata entry for member');
                    }
                })
            } else {
                global.plgManager.logger.info('PLUGIN | SENDEMAIL | EVENT event_new_test_alarm recieved -> NOT FOR this plugin');
            }
        })
    }



    /**
     * Plugin-specific Getters and Setters
     * 
    */


    set from(from) {
        this._from = from;
    }
    get from() {
        return this._from;
    }

    set to(to) {
        this._to = to;
    }
    get to() {
        return this._to;
    }

    set subject(subject) {
        this._subject = subject;
    }
    get subject() {
        return this._subject;
    }

    set plaintext(plaintext) {
        this._plaintext = plaintext;
    }
    get plaintext() {
        return this._plaintext;
    }

    set htmltext(htmltext) {
        this._htmltext = htmltext;
    }
    get htmltext() {
        return this._htmltext;
    }

    set host(host) {
        this._host = host;
    }
    get host() {
        return this._host;
    }

    set port(port) {
        this._port = port;
    }
    get port() {
        return this._port;
    }

    set serverUser(serverUser) {
        this._serverUser = serverUser;
    }
    get serverUser() {
        return this._serverUser;
    }

    set serverPassword(serverPassword) {
        this._serverPassword = serverPassword;
    }
    get serverPassword() {
        return this._serverPassword;
    }

    /**
     * Plugin-specific implementation
     */
    setupTransporter() {
        global.plgManager.logger.debug('PLUGIN | SENDMAIL | Connecting to EMail Server');
        
        
        this.transporter = nodemailer.createTransport({
            host: this.host,    // dinstuehler.eu
            port: this.port,    //465
            secure: true, // upgrade later with STARTTLS
            auth: {
              user: this.serverUser, // "support@alarmiator.de",
              pass: this.serverPassword, // "ThePassword"
            },
            tls: {
                rejectUnauthorized: false
            }
        });
    }

    setupMail() {
        global.plgManager.logger.debug('PLUGIN | SENDMAIL | Composing EMail');
        // setup e-mail data
        this.mailOptions = {
            from: this.from,
            to: this.to,
            subject: this.subject,
            text: this.plaintext,
            html: this.htmltext
        };
        
    }

    sendMail() {
        global.plgManager.logger.debug('PLUGIN | SENDMAIL | Try sending EMail');
        // send mail with defined transport object
        console.log(this.mailOptions);
        this.transporter.sendMail(this.mailOptions, function (error, info) {
            if (error) {
                global.plgManager.logger.error('PLUGIN | SENDEMAIL | Error sending eMail: ' + error);
            }
            if (typeof info !== 'undefined') {
                global.plgManager.logger.info('PLUGIN | SENDEMAIL | EMail sent: ' + info.response);
                console.log('PLUGIN | SENDEMAIL | EMail sent: ' + info.response);
            }
        }.bind(this));
    
    }

    /**
     * Loads configuration for KatSys Service
     * TBD: Needs to be pulled from plugin config store
     */
    loadConfig(callback) {
        global.plgManager.loadConfigFromStore('sendemail', (configRows) => {
            if (configRows !== null) {
                this.config = configRows[0];
                this.config = JSON.parse(this.config.configstore);
                global.plgManager.logger.info('PLUGIN | SENDEMAIL | Configuration reloaded from core database');
                callback(true);
            } else {
                global.plgManager.logger.info('PLUGIN | SENDEMAIL | Found no configuration reloaded in core database');
                callback(false);
            }
        })
    }

    /**
     * returns config parameter for given fieldname
     * @param {string} fieldname 
     */
    getConfigValue(fieldname) {
        var retVal = null;
        this.config.fields.forEach((field) => {
            if (field.fieldname === fieldname) {
                retVal = field.value;
            } 
        });
        return retVal;
    }

    /**
     * initializes all settings. Returns false, if a needed setting is not valid or not set
     * @param {function} callback success (true/false)
     */
    initializePlugin(callback) {
        this.from = this.getConfigValue('mailserverSenderEmailAddress');
        this.to = 'jens@dinstuehler.com';
        this.subject =  this.getConfigValue('mailserverTitlePrefix');
        this.host =  this.getConfigValue('mailserverDomain');
        this.port = 465;
        this.serverPassword =  this.getConfigValue('mailserverPassword');
        this.serverUser = this.getConfigValue('mailserverUsername');

        if ((this.from !== null) && (this.to !== null) && (this.subject !== null) && (this.host !== null) && (this.port !== null) && (this.serverPassword !== null) && (this.serverUser !== null)) {
            return callback(true);
        } else {
            return callback(false);
        }
    }

}

module.exports = sendemail;