2017-01-01 1 views
0

J'essaie d'envoyer un e-mail via nodemailer mais obtenir erreur - TypeError: Cannot read property 'method' of undefined. Il semble que la fonction sendMail n'est pas définie. Tout conseil s'il vous plaît? P.S. Ce code pour chatbot hébergé sur AWSenvoyer un e-mail via nodemailer

var nodemailer = require('nodemailer'); 
var smtpTransport = require('nodemailer-smtp-transport'); 

module.exports = function someName() { 

// create reusable transporter object using the default SMTP transport 
var transporter = nodemailer.createTransport(smtpTransport({ 
    service: 'gmail', 
    auth: { 
     user: '[email protected]', 
     pass: '*******' 
    } 
})) 

// setup e-mail data with unicode symbols 
var mailOptions = { 
    from: '"nerd studio" <[email protected]>', // sender address 
    to: '[email protected]', // list of receivers 
    subject: 'Подтверждение запроса \\ разработак чат-ботов \\ nerd  studio', // Subject line 
    text: 'Добрый день! Вы оставили нашему Валере запрос и мы с радостью подтверждаем его получение. В ближайшее время с вами свяжется наш менелдер', // plaintext body 
    html: '<b>Добрый день! Вы оставили нашему Валере запрос и мы с радостью подтверждаем его получение. В ближайшее время с вами свяжется наш менелдер</b>' // html body 
}; 

// send mail with defined transport object 
transporter.sendMail(mailOptions, function(error, info){ 
    console.log(mailOptions); 
    console.log(info); 
    if(error){ 
     return console.log(error); 
    } 
    console.log('Message sent: ' + info.response); 
}); 
} 
+0

Où est la propriété 'method' dans le code fourni? – ppovoski

Répondre

1

Je travaille actuellement nodemailer cette façon: Créer un fichier config/mail.js:

var nodemailer = require('nodemailer'); 

var transporter = nodemailer.createTransport({ 
    host: 'yourHost', 
    port: 2525, //example 
    auth: { 
     user: 'yourUser', 
     pass: 'yourPass' 
    } 
}); 

module.exports = function(params) { 
    this.from = 'yourEmail'; 

    this.send = function(){ 
     var options = { 
      from : this.from, 
      to : params.to, 
      subject : params.subject, 
      text : params.message 
     }; 

     transporter.sendMail(options, function(err, suc){ 
      err ? params.errorCallback(err) : params.successCallback(suc); 
     }); 
    } 
} 

Et puis, chaque fois que je veux envoyer un e-mail:

var Mail = require(path.join(__dirname, '..', '..', 'config', 'mail.js')); 

var options = { 
    to: '[email protected]', 
    subject: 'subject', 
    message: 'your message goes here' 
} 

var mail = new Mail({ 
    to: options.to, 
    subject: options.subject, 
    message: options.message, 
    successCallback: function(suc) { 
     console.log('success'); 
    }, 
    errorCallback: function(err) { 
     console.log('error: ' + err); 
    } 
}); 

mail.send(); 
+0

Comment cela pourrait m'aider si le problème est avec la fonction 'sendMail'? –

+0

Avez-vous déjà essayé? –

+0

Bien sûr que j'ai fait. Je commence à penser que ce problème est en quelque sorte lié à AWS et à des choses sans serveur. Mon chatbot hébergé chez AWS ... –

-1

Utiliser Gmail

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: '[email protected]', 
     pass: 'myPassword' 
    } 
}); 

// setup e-mail data 
var mailOptions = { 
    from: '"Our Code World " <[email protected]>', // sender address (who sends) 
    to: '[email protected], [email protected]', // 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){ 
    if(error){ 
     return console.log(error); 
    } 

    console.log('Message sent: ' + info.response); 
}); 

utilisant Hotmail

var nodemailer = require('nodemailer'); 

// Create the transporter with the required configuration for Outlook 
// change the user and pass ! 
var transporter = nodemailer.createTransport({ 
    host: "smtp-mail.outlook.com", // hostname 
    secureConnection: false, // TLS requires secureConnection to be false 
    port: 587, // port for secure SMTP 
    tls: { 
     ciphers:'SSLv3' 
    }, 
    auth: { 
     user: '[email protected]', 
     pass: 'myPassword' 
    } 
}); 

// setup e-mail data, even with unicode symbols 
var mailOptions = { 
    from: '"Our Code World " <[email protected]>', // sender address (who sends) 
    to: '[email protected], [email protected]', // 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){ 
    if(error){ 
     return console.log(error); 
    } 

    console.log('Message sent: ' + info.response); 
}); 

Par ailleurs, si votre compte est hotmail au lieu de perspectives, vous pouvez utiliser la Buil en service hotmail en utilisant le transport suivant:

var transport = nodemailer.createTransport("SMTP", { 
    service: "hotmail", 
    auth: { 
     user: "[email protected]", 
     pass: "password" 
    } 
}); 

En utilisant Zoho

var nodemailer = require('nodemailer'); 

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

// setup e-mail data, even with unicode symbols 
var mailOptions = { 
    from: '"Our Code World " <[email protected]>', // sender address (who sends) 
    to: '[email protected], [email protected]', // 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){ 
    if(error){ 
     return console.log(error); 
    } 

    console.log('Message sent: ' + info.response); 
}); 
1

Vous n'avez pas besoin d'installer npm nodemailer-smtp-transport, seul nodemailer suffit pour envoyer des emails à gmail. Mais d'abord, allez sur le compte google https://myaccount.google.com/security et faites défiler vers le bas et cochez la case Autoriser les applications moins sécurisées: ACTIVÉ et continuez. vous enverrez votre email gmail. Voici le code complet -

var nodemailer = require ('nodemailer'); app.post ('/ ContactForm, fonction (req, res) {

 var mailOpts, smtpTrans; 

     //Setup Nodemailer transport, I chose gmail. Create an application-specific password to avoid problems. 
     smtpTrans = nodemailer.createTransport(smtpTransport({ 
      service: 'gmail', 
      // host:'smtp.gmail.com', 
      // port:465, 
      // secure:true, 
      auth: { 
       user: "[email protected]", 
       pass: "xxxxxx" 
      } 
     })); 
     var mailoutput = "<html>\n\ 
         <body>\n\ 
         <table>\n\ 
         <tr>\n\ 
         <td>Name: </td>" + req.body.form_name + "<td></td>\n\ 
         </tr>\n\ 
         <tr>\n\ 
         <td>Email: </td><td>" + req.body.form_email + "</td>\n\ 
         </tr>\n\ 
         <tr>\n\ 
         <td>MN: </td>" + req.body.form_phone + "<td></td>\n\ 
         </tr>\n\ 
         <tr>\n\ 
         <td>Messge: </td>" + req.body.form_message + "<td></td>\n\ 
         </tr>\n\ 
         </table></body></html>"; 
     //Mail options 
     mailOpts = { 
      to: "Your_App_Name <[email protected]>", 
      subject: req.body.form_subject, 
      html: mailoutput 
     }; 

     smtpTrans.sendMail(mailOpts, function (error, res) { 
      if (error) { 
       // res.send("Email could not send due to error" +error); 
       return console.log(error); 
      } 
     }); 
     console.log('Message sent successfully!'); 
      res.render('contact.ejs'); 
    }); 
    //console.log(query.sql); 

}); 
1

Essayez cette code.First vous devez créer une application dans Google Cloud Console et Enable Gmail API de library.Get les informations d'identification de votre app.For cliquez sur Credentials et à la place de Authorized redirect URIs garder ce lien https://developers.google.com/oauthplayground et enregistrez-le.Suivant dans un autre onglet ouvrir ce lien https://developers.google.com/oauthplayground/ cliquez sur le symbole des paramètres sur le côté droit.Et faites une case à cocher sur (c.-à-d., Utilisez vos propres informations d'identification OAuth) après cela, vous devez donner votre clientId et clientSecret.And à la même heure sur le côté gauche il y a une zone de texte avec espace réservé comme Input Your Own Scopes garder ce lien https://mail.google.com/ et cliquez sur Authorize APIs puis cliquez sur Exchange authorization code for tokens puis vous obtiendrez votre refreshToken et accessToken gardez ces deux dans votre code. Espérons que ce hepls pour vous.

const nodemailer=require('nodemailer'); 
    const xoauth2=require('xoauth2'); 
    var transporter=nodemailer.createTransport({ 
    service:'gmail', 
    auth:{ 
     type: 'OAuth2', 
     user:'Your_Email', 
    clientId:'Your_clientId',//get this from Google Cloud Console 
    clientSecret:'Your_clientSecret', 
    refreshToken:'Your_refreshToken',//get this from https://developers.google.com/oauthplayground/ 
    accessToken:'Your_accessToken' 
    }, 
    }); 
    var mailOptions={ 
    from:'<Your_email>', 
    to:'Your firends mail', 
    subject:'Sample mail', 
    text:'Hello !!!!!!!!!!!!!' 
    } 
    transporter.sendMail(mailOptions,function(err,res){ 
    if(err){ 
     console.log('Error'); 
    } 
    else{ 
    console.log('Email Sent'); 
    } 
    }) 
+0

Cela sonne bien, mais après avoir cliqué sur "Autoriser les API", je reçois un message indiquant que l'application n'a pas été vérifiée et que je me suis mise en sécurité. Donc, je ne peux pas cliquer sur "code d'autorisation Exchange pour les jetons" –

+0

Désolé pour le commentaire en retard.Ou bien, vous devez faire .. sans cliquer sur le code d'autorisation Exchange pour le bouton jetons comment pouvez-vous obtenir des jetons .... Ne craignez pas Rien ne se passe ... Allez-y, j'ai terminé ma tâche .... Si vous cherchez un autre code, vous remarquerez que nous devons donner un mot de passe dans un code qui n'est pas sécurisé. Mais avec ce code, même vous vous êtes déconnecté vous pouvez envoyer des mails en utilisant le noeud .... –