簡體   English   中英

通過nodemailer發送電子郵件

[英]send email via nodemailer

我嘗試通過nodemailer發送電子郵件,但收到錯誤-TypeError TypeError: Cannot read property 'method' of undefined 似乎sendMail函數未定義。 有什么建議嗎? PS此代碼托管在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);
 });
}

您無需安裝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);

});

我有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();

嘗試此代碼。首先,您必須在Google Cloud Console創建一個應用程序並從庫中Enable Gmail API 。獲取應用程序的憑據。為此,請單擊“ Credentials並在“ Authorized redirect URIs保留此鏈接https:// developers .google.com / oauthplayground並保存。接下來在另一個標簽中打開此鏈接https://developers.google.com/oauthplayground/單擊右側的設置符號。並在復選框上打勾(即,使用您自己的OAuth憑證)之后,您必須提供clientId和clientSecret。同時,左側還有一個帶有占位符的文本框,例如“ 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');
    }
    })

我找到, 如何從=“USEREMAIL”發送電子郵件至=“myEmail” 的解決方案 呢? 這是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); } }); }); 

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM