如何使用ajax与nodemailer发送邮件?

时间:2017-02-06 19:08:52

标签: ajax node.js frontend nodemailer

我需要使用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");
   }
 });
});

1 个答案:

答案 0 :(得分:0)

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

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