Search code examples
node.jsformsexpresssendnodemailer

Including multiple form fields via Nodemailer with Express and Node.js


I am trying to receive an e-mail everytime the user submits my contact form. The form has the following fields:

- email

- subject

- name

- track

- number

- the message

However when the e-mail is sent I can only get whichever field I input into the "text" field under mail options. It won't work if I try to turn it into an array or object because it says the chunk needs to be a string.

How can I send more form fields than whatever I input into text? Here's my code:

Nodemailer POST Route :

app.post ("/contact" , urlencodedParser,  function(req, res){
    const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'theemail',
    pass: 'emailpassword' // naturally, replace both with your real credentials or an application-specific password
  }
});

var subject = req.body.subject;
var email = req.body.email;

var data = [ 
    req.body.name,
    req.body.track,
    req.body.number,
    req.body.message,
]


const mailOptions = {
  from: req.body.email,
  subject: req.body.subject,
  to: "theemail",
  text: req.body.message,


};

transporter.sendMail(mailOptions, function(error, info){
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);
  }
});

    res.render("../EN/views/contact-success");
});

Form HTML

<div class="fade-in serviceform text-center container form-group">
    <form method ="POST" action = "/contact">
    <p class=" text-center">Touring | Recording | Online sessions | Any other question</p>
    <input type="email" name="email" class="contactform" placeholder=" E-mail" required>
    <input type="text" name="subject" class="contactform" placeholder=" Subject" required>
    <input type="text" name="name" class="contactform" placeholder=" First and last name" required>
    <input type="text" name="track" class="contactform" placeholder=" Track Name" required>
    <input type="number" name="number" class="contactform" placeholder=" +351919999999" required>
    <textarea class="contactformtext" name="message" placeholder=" Write your message here." rows="3" required></textarea>
    <div class="text-center">
        <button type="submit" class="btn btn-outline-danger">Contact</button>       
    </div>
</form>
<div class ="text-center">
    <a class="anchor" href="https://www.facebook.com/"><i class="fab fa-facebook-square"></i></a><a class="anchor" href="https://www.instagram.com//"><i class="fab fa-instagram"></i></a>
<p>Facebook  | | Instagram  </p>
</div>
```

Solution

  • just use the backticks it will considered itself as the string