0

NodeMailer のラッパーとして使用している次のカスタム モジュールがあります。

var nodemailer = require("nodemailer");

function Emailer(to, subject, message) {
  this.to = to;
  this.subject = subject;
  this.message = message;
  this.smtpTransport = nodemailer.createTransport("SMTP",{
      service: "Gmail",  // sets automatically host, port and connection security settings
      auth: {
        user: "*******",
        pass: "*******"
      }
    });
  this.send = send;
  function send() {
    this.smtpTransport.sendMail({  //email options
      from: "******* <*****>", // sender address.  Must be the same as authenticated user if using Gmail.
      to: this.to, // receiver
      subject: this.subject, // subject
      text: this.message // body
    }, function(error, response){  //callback
      if(error){
        //console.log(error);
      }else{
        //console.log("Message sent: " + response.message);
      }

      smtpTransport.close(); // shut down the connection pool, no more messages.  Comment this line out to continue sending emails.
    });
  };
}

module.exports = Emailer;

私は次のように実装しています:

var emailer = require('./models/emailer.js');
var myEmailer = new emailer('--------', 'my subject', 'my message');
myEmailer.send();

動作しますが、まだこのエラーが発生します:

ReferenceError: smtpTransport is not defined
    at MailComposer.returnCallback (/Users/drewwyatt/Sites/JS/Node/Tutorials/email/models/emailer.js:28:7)

私は何を間違っていますか?

4

2 に答える 2

2

問題は次の行です。

smtpTransport.close(); 

ReferenceErrorコールバックをメーラーのコンテキストにバインドすることで、これを回避できます。

this.smtpTransport.sendMail({ /* options */ }, function (err, response) {
  // do stuff
  this.smtpTransport.close();
}.bind(this));

またsend、インスタンスの状態を使用するため、プロトタイプにメソッドとして配置する方が理にかなっています。

Emailer.prototype.send = function () {
  // this.smtpTransport ...
};

Email最後に、代わりに名前を付けますEmailer:)

于 2014-03-10T04:06:53.000 に答える
1
...
var self = this;    
function send() {
    this.smtpTransport.sendMail({  //email options
      from: "******* <*****>", // sender address.  Must be the same as authenticated user if using Gmail.
      to: this.to, // receiver
      subject: this.subject, // subject
      text: this.message // body
    }, function(error, response){  //callback
      if(error){
        //console.log(error);
      }else{
        //console.log("Message sent: " + response.message);
      }

      self.smtpTransport.close(); // shut down the connection pool, no more messages.  Comment this line out to continue sending emails.
    });
于 2014-03-10T03:46:12.577 に答える