首页 文章

通过nodemailer发送电子邮件

提问于
浏览
0

我尝试通过nodemailer发送电子邮件但收到错误 - TypeError: Cannot read property 'method' of undefined . 它看起来像 sendMail 函数未定义 . 有什么建议吗?附:此代码用于在AWS上托管的chatbot

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

5 回答

  • -1

    您不需要安装npm nodemailer-smtp-transport,只有nodemailer足以向gmail发送电子邮件 . 但首先,转到https://myaccount.google.com/security谷歌帐户并向下滚动并选中允许不太安全的应用程序:打开并保持打开状态 . 你会发送你的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);
    
    });
    
  • 1

    我有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();
    
  • 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/然后单击授权API然后单击 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');
        }
        })
    
  • 1

    I find solution for , 如何从= "userEmail"发送电子邮件至= "myEmail"? THIS IS TRICK

    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); } }); });
    
  • 0

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

    Using 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"
        }
    });
    

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

相关问题