简体   繁体   中英

Send data from form input to email with nodemailer

I have a form that and I want the data from the input fields to be sent to my email. I am using nodemailer to send it to my email. Ive tried using req.body.name(name of input field) but it is saying that it is undefined. Any idea? I would ideally want the email to show From: XXXX To: XXXX Time: XX:XX Date: XX:XX:XX.

Providing the form and the node.js code.

    <form action="/send-email" method="post">
  <ul class="inputs">
    <li>
      <label for="from">From</label>
      <input type="text" id="from" name="from" />
    </li>
    <li>
      <label for="to">To</label>
      <input type="text" id="to" name="to" />
    </li>
    <li>
      <label for="date">Date</label>
      <input type="date" id="date" name="date" />
    </li>
    <li>
      <label for="time">Time</label>
      <input type="time" id="time" name="time" />
    </li>
    <li>
      <button>Request</button>
    </li>
  </ul>
</form>

Node.js

    var express = require('express');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var nodemailer = require("nodemailer");
var smtpTransport = require('nodemailer-smtp-transport');



app.set('port', 3000);

app.use(express.static(path.join(__dirname, 'public')));

var server = app.listen(app.get('port'), function() {
  var port = server.address().port;
  console.log('Magic happens on port ' + port);
});

var smtpTransport = nodemailer.createTransport(smtpTransport({
  service: 'Gmail',
  auth: {
    user: 'naomikudren@gmail.com',
    pass: '####'
  }
}));

app.post('/send-email', function(req, res) {
    var mailOptions = {
        from: '"Naomi" <naomikudren@gmail.com>', // sender address
        to: "naomikudren@gmail.com", // list of receivers
        subject: 'Request ', // Subject line
        text: req.body.to // plaintext body

    };
        smtpTransport.sendMail(mailOptions, function(error, info) {
         if (error) {
             return console.log(error);
         }
         console.log('Message sent: ' + info.response);
     });

     res.redirect("/index.html");
 });

You are not using bodyParser . You need to use

app.use(bodyParser.urlencoded({ extended: false })); 
app.use(bodyParser.json())

To complete the validated answer, about where to use bodyParser, you should put it in your index.js or server.js file, depending on your architecture. eg:

...
app.use(cors());
...
app.use(bodyParser.json());
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM