【问题标题】:send email via nodemailer通过 nodemailer 发送电子邮件
【发布时间】:2017-05-16 01:59:27
【问题描述】:

我尝试通过 nodemailer 发送电子邮件但收到错误 - TypeError: Cannot read property 'method' of undefined。看起来sendMail 函数没有定义。请问有什么建议吗? 附言此代码用于托管在 AWS 上的聊天机器人

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: '7384093@gmail.com',
      pass: '*******'
  }
}))

// setup e-mail data with unicode symbols
var mailOptions = {
  from: '"nerd studio" <7384093@gmail.com>', // sender address
  to: '7384093@gmail.com', // 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);
 });
}

【问题讨论】:

  • 提供的代码中method的属性在哪里?

标签: node.js nodemailer


【解决方案1】:

你不需要安装 npm nodemailer-smtp-transport,只需 nodemailer 就足以发送电子邮件到 gmail。但首先,转到https://myaccount.google.com/security google 帐户并向下滚动并选中允许不太安全的应用程序:打开并保持打开。您将发送您的 gmail 电子邮件。这是完整的代码 -

var nodemailer = require('nodemailer');
app.post('/contactform', function (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: "xxxxxx@gmail.com",
                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 <xxxxxxxx@gmail.com>",
            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);

});

【讨论】:

    【解决方案2】:

    我的 nodemailer 目前以这种方式工作:创建文件 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);
            });
        }
    }
    

    然后,任何时候我想发送电子邮件:

    var Mail = require(path.join(__dirname, '..', '..', 'config', 'mail.js'));
    
    var options = {
        to: 'example@example.com',
        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();
    

    【讨论】:

    • 如果问题出在sendMail 函数上,它对我有何帮助?
    • 我确实做到了。我开始认为这个问题与 AWS 和无服务器的东西有关。我的聊天机器人托管在 AWS...
    • 使用你的解决方案我看到服务器试图访问我的邮件服务 gmail 但我没有收到电子邮件....我猜sendMail 函数至少应该抛出一个错误?!还是可能是 gmail 阻止了我的电子邮件?
    • 错误未定义吗?我正在使用 smtp2go,不妨试试那个。
    【解决方案3】:

    试试这个代码。首先,您必须在库中的Google Cloud ConsoleEnable Gmail API 中创建一个应用程序。获取您的应用程序的凭据。为此,请单击Credentials 并代替Authorized redirect URIs保持此链接https://developers.google.com/oauthplayground 并保存它。接下来在另一个选项卡中打开此链接 https://developers.google.com/oauthplayground/ 单击右侧的设置符号。然后在复选框上打勾(即,使用您自己的 OAuth 凭据)您必须提供您的 clientId 和clientSecret.And 同时在左侧有一个带有占位符的文本框,如Input Your Own Scopes 保留此链接https://mail.google.com/ 然后点击 Authorize APIs 然后点击 Exchange authorization code for tokens 然后你会得到你的 refreshTokenaccessToken 将这两个保留在你的代码中。希望这对你有帮助。

        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');
        }
        })
    

    【讨论】:

    • 这听起来不错,但是在我点击“授权 API”后,我会被定向到一个屏幕,上面写着应用程序尚未经过验证之类的内容,请注意安全。所以我不能点击“兑换令牌的授权码”
    • 抱歉,评论迟了。当然,您必须这样做..不点击“交换令牌的授权码”按钮,您如何获得令牌....不要害怕什么都没有发生...去吧我完成了我的任务....如果您搜索任何其他代码,您会注意到我们必须在不安全的代码中提供电子邮件密码。但是使用此代码,即使您从邮件中注销,您也可以使用节点发送邮件。 ...
    【解决方案4】:

    我找到了解决方案, 如何将电子邮件从="userEmail" 发送到="myEmail"? 这是技巧

    var nodemailer = require('nodemailer'); router.post('/contacts-variant-2', (req, res, next) => { var name=req.body.name; var email=req.body.email; var message=req.body.message; const output=`
    <h3>Contact Details</h3>
    <ul>
      <li>Name is : ${req.body.name}</li>
      <li>Email is : ${req.body.email}</li>
    </ul>
    <h3>Message</h3>
    <p>${req.body.message}</p>
    `; var transporter = nodemailer.createTransport({ service: 'yahoo', auth: { user: 'create_new_email@yahoo.com', pass: 'password' } }); var mailOptions = { from:'create_new_email@yahoo.com', to:'myFriend@gmail.com', subject: name, text: 'Your have a new
    contact request', html:output }; transporter.sendMail(mailOptions, function(error, info){ if (error) { console.log("errors is somthing "+error); res.send(404); } else { console.log('Email sent: ' + info.response); res.send(200); } }); });

    【讨论】:

      【解决方案5】:

      使用 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: '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){
          if(error){
              return console.log(error);
          }
      
          console.log('Message sent: ' + info.response);
      });
      

      使用 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: 'mymail@outlook.com',
              pass: 'myPassword'
          }
      });
      
      // setup e-mail data, even with unicode symbols
      var mailOptions = {
          from: '"Our Code World " <mymail@outlook.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){
          if(error){
              return console.log(error);
          }
      
          console.log('Message sent: ' + info.response);
      });
      

      或者,如果您的帐户是 hotmail 而不是 Outlook,您可以通过以下传输方式使用内置 hotmail 服务:

      var transport = nodemailer.createTransport("SMTP", {
          service: "hotmail",
          auth: {
              user: "user@hotmail.com",
              pass: "password"
          }
      });
      

      使用 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: 'myzoho@zoho.com',
              pass: 'myPassword'
          }
      });
      
      // setup e-mail data, even with unicode symbols
      var mailOptions = {
          from: '"Our Code World " <myzoho@zoho.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){
          if(error){
              return console.log(error);
          }
      
          console.log('Message sent: ' + info.response);
      });
      

      【讨论】:

        猜你喜欢
        • 2021-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-08
        • 2019-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多