sending html input values

I want to send a message, which has values entered in an input box. For example, “Hey, my name is firstname” (fname: the input value) and “lastname” (lname: the input value).

How can I include entered values from the input box in the message body?

Here’s my code:

<!DOCTYPE html> 
<html> 
    
  <head> 
    <title>Sending Mail</title> 
    <script src="https://smtpjs.com/v3/smtp.js"></script> 
    <script type="text/javascript"> 
        function sendEmail() { 
        Email.send({ 
            Host: "smtp.gmail.com", 
            Username: "", 
            Password: "", 
            To: '', 
            From: "", 
            Subject: "", 
            Body: "",  // send entered values from input box
        }) 
            .then(function (message) { 
            alert("Mail has been sent successfully") 
            }); 
        } 
    </script> 
  </head> 

  <body> 
    <form method="post"> 
     <input type="text"  name="fname">  
         <input type="text"  name="lname">
        <input type="button" value="Send Mail"
            onclick="sendEmail()" /> 
    </form> 
  </body> 
    
</html> 

Answer

You can use template literals like the example below or you can concatenate them with the + symbol like I do in emailBody variable below.

<!DOCTYPE html> 
<html> 

  <head> 
    <title>Sending Mail</title> 

    <script src="https://smtpjs.com/v3/smtp.js"></script> 

    <script type="text/javascript"> 
      function sendEmail() {
        var firstName = document.querySelector('input[name="fname"]').value;
        var lastName = document.querySelector('input[name="lname"]').value;
        
        var emailBody = 'Welcome ' + firstName + ' ' + lastName;
        
        Email.send({ 
          Host: "smtp.gmail.com", 
          Username: "", 
          Password: "", 
          To: '', 
          From: "", 
          Subject: "", 
          Body: `Welcome ${firstName} ${lastName}`,  // send entered values from input box
        }).then(function (message) { 
          alert("Mail has been sent successfully") 
        }); 
      } 
    </script> 
  </head> 

  <body> 
    <form method="post"> 
      <input type="text"  name="fname">  
      <input type="text"  name="lname">
      <input type="button" value="Send Mail" onclick="sendEmail()" /> 
    </form> 
  </body> 

</html>

Leave a Reply

Your email address will not be published. Required fields are marked *