Something like this should work:
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);
}
});
}
};
Then use it like this:
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();
I don't have access to gmail at the moment to test the sending etc, but this should work in principal.
There are various syntax issues in your initial example which I fixed.
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.
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.
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);
}
});
}
};
Calling it looks like this:
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();