【问题标题】:How use ajax with nodemailer for send mails?如何使用 ajax 和 nodemailer 发送邮件?
【发布时间】:2017-06-23 20:16:13
【问题描述】:

我需要使用 ajax 使用 nodemailer 发送邮件以显示消息确认,而无需重新加载我的页面。

另一个问题是如果在前端使用代码 ajax 发送两封邮件

=============================

app.js

app.post('/enviar', function(req,res){

 var name = req.body.nombre;
 var mail = req.body.correo;
 var messege = req.body.mensaje;
 var mail_from = "servicios@fractalservicios.com";
 var subject_from = "Contact web fractal nodejs";

 var transporter  = nodemailer.createTransport(smtpTransport({
  host: "*****",
  port: ***,
  auth: {
   user: "****",
   pass: "****"
  }
 }));

 var mailOptions = {
   from: name + ' ' + mail, // sender address
   to: mail_from, // list of receivers
   subject: subject_from , // Subject line
   html: messege // html body
};

 transporter.sendMail(mailOptions,function(error,result){
  if(error){
   console.log(error);
   console.log("salio mal");
   //res.end("error");
   res.render('error',{titulo: 'error al enviar menmsaje'});
  }else{
   console.log("Message sent: " + res.message);
   console.log("correcto");
   res.redirect('/');
   //res.render('enviado',{titulo: 'mensaje enviado'});
  }
  //res.redirect('/');
 });
})

build.js => 前端

var nombre = $('#nombre').val();
var correo = $('#correo').val();
var mensaje = $('#mensaje').val();

var enviar_info = {
 "nombre": nombre,
 "correo": correo,
 "mensaje": mensaje
};

$('.send_mail').on('click',function(){
 $.ajax({
   type: "POST",
   url: "/enviar",
   data: JSON.stringify(enviar_info),
   contentType:"application/json; charset=utf-8",
   dataType: 'json',
   success: function(e){
    alert("genial se envio tu mensaje");
   }
 });
});

【问题讨论】:

    标签: ajax node.js frontend nodemailer


    【解决方案1】:

    我最近遇到了同样的问题,我尝试了以下方法。它对我来说就像一个魔法,迟到的答案,但我相信其他人可能需要它......

     $(function() {
      $('#contact-form').on('submit', function(event) {
        event.preventDefault();
        let name = $('input[name="name"]').val(),
           company = $('input[name="company"]').val(),
           email = $('input[name="email"]').val(),
           phone = $('input[name="phone"]').val(),
           message = $('textarea[name="message"]').val();
    
        $.ajax({
          url: '/',
          method: "POST",
          contentType: 'application/json',
          data: JSON.stringify({
            name,
            company,
            email,
            phone,
            message
          }),
          success: function(response) {
            console.log(response);
          },
          fail: function(error) {
            console.log(error);
          }
        });
      });
    });
    

    在 server.js 中

    app.post('/', function(req, res) {
      const output = `
        <p>You have a new contact request</p>
        <h3>contact details</h3>
        <ul>
          <li>Name: ${req.body.name}</li>
          <li>Company: ${req.body.company}</li>
          <li>Email: ${req.body.email}</li>
          <li>Phone: ${req.body.phone}</li>
        </ul>
        <h3>Message</h3>
        <p>${req.body.message}</p>
      `;
    
      let transporter = nodemailer.createTransport({
        service: 'gmail',
        host: 'mail.domain.com',
        port: 465,
        tls: {
          rejectUnauthorized: false, //NOTE: you only need to set rejectUnauthorized to false if you are running on a local server, you can remove it after testing
        }
      });
    
      let mailOptions = {
        from: `nodemailer contact ${req.body.email}`,
        to: 'info@domain.com',
        subject: 'User Form Contact',
        html: output
      };
    
      transporter.sendMail(mailOptions, function(error, info) {
        if (error) {
          return console.log(error);
        }
    
        console.log('Message sent: %s', info.messageId);
        console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
    
        res.send({
          msg: 'Email has been sent!'
        });
      });
    });
    

    【讨论】:

    • 谢谢,我发现这很有用。
    猜你喜欢
    • 2017-12-06
    • 2018-07-14
    • 1970-01-01
    • 2021-12-28
    • 2023-03-27
    • 2015-05-19
    • 1970-01-01
    相关资源
    最近更新 更多