Building a Contact form to send email Javascript

Creating a functional contact form on your website is an essential part of engaging with users, collecting leads, and providing support. However, one common challenge for developers is ensuring the form can send emails directly using JavaScript, especially when working on the front-end without a dedicated back-end server. In this article, we’ll explore a secure and efficient way to build a contact form using HTML, CSS, and JavaScript, with help from third-party services where appropriate.

TLDR (Too Long, Didn’t Read)

A contact form with frontend JavaScript alone cannot send SMTP emails directly, due to browser limitations and security risks. To send emails, use an email-sending API like EmailJS or Formspree. This article walks through creating the HTML form, capturing form data with JavaScript, and sending it using a service securely. You’ll also learn how to validate form inputs and provide user feedback.

1. Understanding the Limitations of JavaScript

First, it’s crucial to understand that JavaScript running in the browser cannot send SMTP email messages directly. This is due to two main reasons:

  • Security risks: Exposing SMTP credentials in client-side code can compromise your account or server.
  • Browser limitations: Browsers do not support SMTP connections out-of-the-box, which limits direct email-sending capabilities.

To work around this, we rely on third-party services that provide APIs for sending emails or use a back-end server as a communication bridge.

2. Choosing the Right Email Service

There are several third-party platforms designed to allow client-side web applications to send emails securely and efficiently. Popular options include:

  • EmailJS – Enables you to send emails directly from JavaScript without a back-end. Very simple to configure.
  • Formspree – Allows sending form submissions to email addresses, no backend needed.
  • FormSubmit – Plug-and-play solution for small forms with minimal configuration.

For this step-by-step guide, we’ll use EmailJS due to its wide adoption, documentation, and user-friendly approach.

3. Creating the HTML Contact Form

Here’s an example of a basic contact form written in HTML:

<form id="contact-form">
  <label for="name">Name:</label>
  <input type="text" id="name" name="user_name" required><br>

  <label for="email">Email:</label>
  <input type="email" id="email" name="user_email" required><br>

  <label for="message">Message:</label>
  <textarea id="message" name="message" required></textarea><br>

  <button type="submit">Send</button>
</form>
<div id="form-status"></div>

This form includes name, email, and a message field. All fields are marked required for better user input validation.

4. Installing and Setting Up EmailJS

To integrate EmailJS with your form, follow these steps:

  1. Go to https://www.emailjs.com and create a free account.
  2. Create a new email service and email template.
  3. Take note of your Service ID, Template ID, and User ID.
  4. Include the EmailJS SDK in your HTML file using this script:
<script type="text/javascript"
  src="https://cdn.emailjs.com/dist/email.min.js"></script>
<script type="text/javascript">
  (function(){
    emailjs.init("your_user_id"); // Replace with your actual User ID
  })();
</script>

5. Capturing Form Data with JavaScript

Add the following JavaScript to capture the form data and use EmailJS to send the email:

<script>
document.getElementById("contact-form").addEventListener("submit", function(event) {
  event.preventDefault();

  emailjs.sendForm("your_service_id", "your_template_id", this)
    .then(function(response) {
       document.getElementById("form-status").innerHTML = "Message sent successfully!";
    }, function(error) {
       document.getElementById("form-status").innerHTML = "Failed to send email. Please try again.";
    });
});
</script>

This code binds an event listener to your form and prevents the default submission. It uses the EmailJS method sendForm to send the email and then notifies the user of success or failure.

6. Validating User Inputs

Client-side validation ensures only valid data is processed. HTML5 gives us a head start with input types like email and the required attribute, but you can take it further with JavaScript:

<script>
function validateForm() {
  const email = document.getElementById("email").value;
  const name = document.getElementById("name").value;
  const message = document.getElementById("message").value;

  if (!email || !name || !message) {
    alert("All fields are required.");
    return false;
  }
  return true;
}

document.getElementById("contact-form").addEventListener("submit", function(event) {
  if (!validateForm()) {
    event.preventDefault();
    return;
  }
});
</script>

Note: Always validate inputs both on client and server (if applicable). Front-end validation is user-friendly, but it should not be solely relied upon if a backend exists.

7. Styling the Form

Improve usability and appearance with basic CSS styling:

<style>
form {
  max-width: 400px;
  margin: 20px auto;
}
input, textarea {
  width: 100%;
  padding: 10px;
  margin-top: 5px;
  margin-bottom: 15px;
}
button {
  padding: 10px 20px;
  background-color: #0B5ED7;
  color: #fff;
  border: none;
}
#form-status {
  text-align: center;
  margin-top: 20px;
}
</style>

This simple styling centers the form and ensures accessibility with large clickable buttons and readable inputs.

8. Security Considerations

Even though services like EmailJS are designed with security in mind, you must still follow best practices:

  • Never hard-code sensitive tokens or credentials in production code.
  • Consider using environment variables or deploying through secure hosting solutions that obscure user IDs.
  • Set domain restrictions in the EmailJS dashboard to prevent unauthorized use.

9. Alternatives and Advanced Options

If you want more control, consider developing a small backend (Node.js, PHP, Flask) to handle the form and send emails using an SMTP library such as Nodemailer or PHPMailer. This is ideal for commercial apps or when integrating with CRMs, support systems, or databases.

Conclusion

Building a contact form using JavaScript to send emails is possible and practical when paired with the right tools. Although client-side JavaScript can’t communicate with email servers directly, using APIs like EmailJS allows a secure and user-friendly solution.

By following this guide, you’ve learned how to:

  • Structure a contact form using HTML
  • Securely send emails using EmailJS
  • Validate input and provide user feedback

Always prioritize data security and consider your application’s scale when choosing between client-side services or a dedicated backend.