Session.send () не работает: «сессия не определена» - PullRequest
0 голосов
/ 01 декабря 2018

Я пытаюсь использовать session.send вместо console.log в transporter.sendMail, чтобы пользователь знал, когда электронное письмо было успешно отправлено, но оно не работает.
Ошибка: "сеанс не определен".
Вот так выглядит мой код:

var nodemailer = require('nodemailer');

// Create the transporter with the required configuration for Gmail
// change the user and pass !
var transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true, // use SSL
    auth: {
        user: 'myemail@gmail.com',
        pass: 'myPassword'
    }
});

// setup e-mail data
var mailOptions = {
    from: '"Our Code World " <myemail@gmail.com>', // sender address (who sends)
    to: 'mymail@mail.com, mymail2@mail.com', // list of receivers (who receives)
    subject: 'Hello', // Subject line
    text: 'Hello world ', // plaintext body
    html: '<b>Hello world </b><br> This is the first email sent with Nodemailer in Node.js' // html body
};

// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info,session){
    if(error){

        return console.log(error);
    }

    session.send('Message sent: ' + info.response);
}
);

Ответы [ 3 ]

0 голосов
/ 02 декабря 2018

transporter.sendMail(mailOptions, function(error, info , session)

Вы не используете правильное определение функции, поскольку обратный вызов транспорта. SendMail может иметь только два параметра (error & info).Взгляните на пример Nodemailer .

В вашем случае это будет выглядеть так.Просто убедитесь, что вы используете этот фрагмент, где доступен контекст session.

transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
        return session.error(error);
    }

    session.send('Message sent: ' + info.messageId);
});
0 голосов
/ 05 декабря 2018

это пример того, как это сделать.Просто убедитесь, что вы вызываете этот метод в контексте сеанса, например:

const sendmail = require('./email'); // in case you have the class called email

bot.dialog('/', function(session) {


sendmail.sendmail(session);


session.send("hello")

});

function sendmail(session){

  var nodemailer = require('nodemailer');

  // Create the transporter with the required configuration for Outlook
  // change the user and pass !
  var transport = nodemailer.createTransport( {
      service: "hotmail",
      auth: {
          user: "",
          pass: ""
      }
  });

  // setup e-mail data, even with unicode symbols
  var mailOptions = {
      from: '"Our Code World " <shindar902009@hotmail.com>', // sender address (who sends)
      to: 'shindar902009@hotmail.com', // list of receivers (who receives)
      subject: 'Hello ', // Subject line
      text: 'Hello world ', // plaintext body
      html: '<b>Hello world </b><br> This is the first email sent with Nodemailer in Node.js' // html body
  };

  // send mail with defined transport object
  transport.sendMail(mailOptions, function(error, info){
      if(error){
          return console.log(error);
      }

      session.send('Message sent');

  });


}
module.exports.sendmail = sendmail;
0 голосов
/ 01 декабря 2018

Я только что запустил этот фрагмент, заменяя имя пользователя и пароль соответствующим образом, и получил следующее:

{ Error: Invalid login: 534-5.7.14 <https://accounts.google.com/signin/continu> Please log in via
534-5.7.14 your web browser and then try again.
534-5.7.14  Learn more at
534 5.7.14  https://support.google.com/mail/answer/ - gsmtp
    at SMTPConnection._formatError (C:\projects\nodemailertest\node_modules\nodemailer\lib\smtp-connection\index.js:605:19)
    at SMTPConnection._actionAUTHComplete (C:\projects\nodemailertest\node_modules\nodemailer\lib\smtp-connection\index.js:1340:34)
    at SMTPConnection._responseActions.push.str (C:\projects\nodemailertest\node_modules\nodemailer\lib\smtp-connection\index.js:378:26)
    at SMTPConnection._processResponse (C:\projects\nodemailertest\node_modules\nodemailer\lib\smtp-connection\index.js:764:20)
    at SMTPConnection._onData (C:\projects\nodemailertest\node_modules\nodemailer\lib\smtp-connection\index.js:570:14)
    at TLSSocket._socket.on.chunk (C:\projects\nodemailertest\node_modules\nodemailer\lib\smtp-connection\index.js:522:47)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at TLSSocket.Readable.push (_stream_readable.js:134:10)
  code: 'EAUTH',
  response: '534-5.7.14 <https://accounts.google.com/signin/continue?..._sniped> Please log in via\n534-5.7.14 your web browser and then try again.\n534-5.7.14  Learn more at\n534 5.7.14  https://support.google.com/mail/answer/78 - gsmtp',
  responseCode: 534,
  command: 'AUTH PLAIN' }

Более того, я получил письмо от Google:

Someone just used your password to try to sign in to your account from a non-Google app. Google blocked them, but you should check what happened. Review your account activity to make sure no one else has access.

Вы уверены, что это код, который вы запускаете?Сообщение об ошибке «сеанс не определен» выглядит как синтаксическая ошибка.

...