Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Something like this should work:</p> <pre><code>var util = require('util'); var events = require('events'); var nodemailer = require("nodemailer"); var smtpTransport = nodemailer.createTansport("SMTP", { service: "GMAIL", auth: { user : "mail@mail.com", pass : "pass" } }); module.exports = function(from, to, subject){ this.from = from; this.to = to; this.subject = subject; this.events = new events.EventEmitter(); //.... this.send = function(){ var options = { from : this.from, to : this.to }; smtpTransport.sendMail(options, function(err, success) { if(err){ this.events.emit('error', err); } if(success){ this.events.emit('success', success); } }); } }; </code></pre> <p>Then use it like this:</p> <pre><code>var Mail = require('./mail'); var mail = new Mail(); mail.from = "email@mail.com"; mail.to = "email@mail.com"; mail.events.on("error", function(err){ console.log("Mail not send"); }); mail.events.on("success", function(success){ console.log("Mail send"); }); mail.send(); </code></pre> <p>I don't have access to gmail at the moment to test the sending etc, but this should work in principal.</p> <p>There are various syntax issues in your initial example which I fixed.</p> <p>The main thing to bare in mind is that you need to expose the EventEmitter to the client code so that they can register for callbacks and be sure to register the callbacks before sending the email.</p> <p>You can do this without using the EventEmitter as well, by passing in success and failure callback functions. Which will make it a bit simpler.</p> <pre><code>module.exports = function(params){ this.from = params.from; this.to = params.to; this.subject = params.subject; this.successCallback = params.successCallback; this.errorCallback= params.errorCallback; this.send = function(){ var options = { from : this.from, to : this.to }; smtpTransport.sendMail(options, function(err, success) { if(err){ this.errorCallback(err); } else{ this.successCallback(success); } }); } }; </code></pre> <p>Calling it looks like this:</p> <pre><code>var Mail = require('./mail'); var mail = new Mail({ from : "email@mail.com", to : "email@mail.com", subject : "subject", successCallback : function(success){ console.log("Mail send"); }, errorCallback : function(err){ console.log("Mail not send"); } }); mail.send(); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload