0

I am building a contact form with multiple input lines, and would like information from the form to be sent to my email address. For instance, I have a line for the user's email address, a line for the user's budget, and a line for the user's city. These variables are denoted by "email", "budget", and "city", respectively. As a result, I am using req.body.email as the text in nodemailer.

The issue is that I am only able to put one of the variables in the text section of the email. Here is my code to better explain what I mean.

const mailOptions = {
from: req.body.email,
to: 'fakeemail@gmail.com',
subject: 'New message from Ogma',
text: req.body.email
    }

What is the syntax I have to use in order to also put req.body.budget and req.body.city in the text section?

Thank you!

Edit: Here is the rest of my JS code because I'm not sure what's wrong

const form = document.getElementById('login');
let subject = document.getElementById('subject');
let level = document.getElementById('level');
let inperson = document.getElementById('inperson');
let where = document.getElementById('where');
let details = document.getElementById('details');
let email = document.getElementById('email');



form.addEventListener('submit', (e)=>{
e.preventDefault();
console.log('submit clicked')

let formData = {
    subject: subject.value,
    level: level.value,
    inperson: inperson.value,
    where: where.value,
    details: details.value,
    email: email.value
}

let xhr = new XMLHttpRequest();
xhr.open('POST', '/');
xhr.setRequestHeader('content-type', 'application/json');
xhr.onload = function() {
    console.log(xhr.responseText);

    if (xhr.responseText == 'success'){
        alert('Email sent');
        subject.value = '';
        level.value = '';
        inperson.value = '';
        where.value = '';
        details.value = '';
        email.value = '';
    }else{
        alert('Invalid login')
    }

}

xhr.send(JSON.stringify(formData));

})
  • Who is receiving the email? Do they need to be able to disassemble the email back into the individual parts? – Bergi May 18 '22 at 23:38
  • You might want to simply concatenate them with a few newlines. `[req.body.email, req.body.budget, req.body.city].join('\n\n')` might do. Or interpolate them into whatever string template you'd like. – Bergi May 18 '22 at 23:39
  • Thank you Bergi! That fixed the problem :) – C. Programmer May 25 '22 at 04:47

1 Answers1

0

If something isn't very wrong, then req.body should be an object. Something like

{
    email: "some@mail.com",
    budget: 12345,
    city: "Paris"
}

which means you should be able to just do

text: req.body

That way you can then access the object either but using mailOptions.text and working with it as you would with an object, or reference it direcly since it's a nested object - mailOptions.text.budget.

It all depends on what you do with the mailOptions afterwards.

Dropout
  • 13,653
  • 10
  • 56
  • 109