我使用 nodejs nodemail 发送邮件,所以我有一部分想在发送邮件时创建事件错误和成功,而不是使用回调
var util = require('util');
var event = require('events');
var nodemailer = require("nodemailer");
var smtpTransport = nodemailer.createTansport("SMTP", {
service: "GMAIL",
auth: {
user : "mail@mail.com",
pass : "pass"
}
});
mail.exports = function(from, to, subject ...){
this.from = from;
this.to = to;
this.subject = subject;
....
this.send = function(){
var options = {
from = this.from;
to = this.to;
};
var obj = this.send;
event.Eventemitter.call(obj);
smtpTransport.sendMail(options, function(err, success) {
if(err){
obj.emit('error', err);
}
if(success){
obj.emit('success', success);
}
});
}
};
然后打电话给邮件服务
var Mail = require('./mail');
var mail = new Mail();
mail.from = "email@mail.com";
mail.to = "email@mail.com";
...
mail.send(); //the mail is send
邮件已发送,但我不知道邮件是否发送
mail.send()
.on("error", function(err){
console.log("Mail not send");
})
.on("success", function(success){
console.log("Mail send");
});
我遵循了以下教程 http://www.sitepoint.com/nodejs-events-and-eventemitter/