Javascript send form to email

Contact forms are essential part of every website especially portfolio websites. This is how one gets contacted.

However, we have many portfolios flying around without a contact form or at least, a working contact form. The reason is usually that the frontend person do not know how to create the backend functionality of the contact form. That is understandable. This is part of the reasons Emailjs was created. It is also free.

Emailjs is a free tool that allows you to Send Email Directly From frontend with No server code. You can send and receive up to 200 emails using the free package. This is reasonable if you ask me. You can also upgrade with just a little token.

In this tutorial, I will walk you through building a contact form that sends email directly to your email address. We will build it in plain JavaScript. We will also look at React in the next tutorial. Let's get to it.

Javascript send form to email

Create and Setup a free Account

  • Go to the signup page and create an account.

You should now be in your dashboard like so:

Add a new Email Service

Email Service could be Personal or Transactional. You can read more on that here.

Since we just need to receive personal emails sent to us via our website, we will stick to the Personal Email Service.

  • On the side menu, click on Email Services:

  • Click on Add Email Service:

  • Select Gmail from the dialogue box:

  • You can now see your Service ID in the screen that follows

  • Click on Connect Account just below the Service ID.

Do not uncheck Send test email to verify configuration if you want to receive a test email confirming your connection

You should now have the gmail authorization screen. Please select the email you want to use

  • Check all boxes and Continue

  • When the connection is successful, you should now be back to this screen with a confirmation message: Connected as like the screen below

You can always come back here to disconnect

I also got an email to confirm my connection to Emailjs:

  • Finally, click on Create Service to complete Email Service creation

You should now have a new service added like so:

Nice one!!! Do keep the Service ID because you will be needing it shortly.

Create Your Email Template

The Email Templates is used to design how we want the emails sent to us will look. So to do that, go to the side menu in the dashboard and click the Email Templates link

  • Click on Create New Template

You will now have the template screen like so:

You will notice that the screen looks just like you are about to create a new email.

For every field, you can fill in a default text you will like to get. However, any text in side double curly braces, becomes a variable. For example, in the email body, {{message}} is a variable. When you create a form, the input box with the name: message, is to collect the text that will be rendered in the email body where {{message}} is situated.

I hope that makes sense. You will understand more as we proceed anyways.

  • Let's now change the email content a little. For the subject field, just enter {{subject}} and for the email body, enter the following:


{{message}}

{{name}}
{{email}}

Enter fullscreen mode Exit fullscreen mode

My screen now looks like this:

Click on Save

You may choose to test it by clicking the Test It Button next to the Save Button. It's pretty straight forward.

This time for us to build our JavaScript application has now arrived.

Javascript send form to email

JavaScript

Starter Project

Get the starter code here or just create a project with a file: index.html and add the following code:



 lang="en">
  
     charset="UTF-8" />
     name="viewport" content="width=device-width, initial-scale=1.0" />

    
    
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm//dist/css/bootstrap.min.css"
      integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
      crossorigin="anonymous"
    />
    </span>JavaScript Emailjs<span>
  
  
     class="container">
       class="row">
         class="col align-self-center">
           class="text-center">Email - JavaScript Contact Form
          
           id="myForm">
            
             class="form-group">
               for="name">Name
              
                type="name"
                name="name"
                class="form-control"
                id="name"
                placeholder="enter your name"
              />
            
class="form-group"> for="email">Email address type="email" name="email" class="form-control" id="email" placeholder="enter your email" /> class="form-group"> for="subject">Subject type="text" name="subject" class="form-control" id="subject" placeholder="enter email subject" /> class="form-group"> for="message">Message class="form-control" id="message" name="message" rows="5"> type="submit" class="btn btn-primary">Submit

Enter fullscreen mode Exit fullscreen mode

After setting it up in your local machine, you should have the following screen:

In the code, the Message field name is message. That was initially omitted

  • Install EmailJs by adding the following script at the bottom


    <script
      type="text/javascript"
      src="https://cdn.jsdelivr.net/npm/emailjs-com@3/dist/email.min.js"
    ></script>

    <script type="text/javascript">      (function () {
        emailjs.init("YOUR_USER_ID");
      })();
    </script>

Enter fullscreen mode Exit fullscreen mode

*Do not forget to put YOUR_USER_ID to your own user id *

To get your USER_ID, go to your dashboard and click on the Integrations link on the side menu. You should be on a page like this:

Your USER_ID is down below under the API Keys

  • Now, back to our code, start another script below with the following code inside:


<script>
emailjs.sendForm("YOUR_SERVICE_ID", "YOUR_TEMPLATE_ID", "#myForm")
</script>

Enter fullscreen mode Exit fullscreen mode

The line of code you see is all you need to send messages from your form to your email address through EmailJS. You will need to change "YOUR_SERVICE_ID" and "YOUR_TEMPLATE_ID" to your actual values.

To get YOUR_SERVICE_ID, click on the Email Services link in your dashboard's side menu

To get YOUR_TEMPLATE_ID, click on the Email Templates link in your dashboard's side menu and go to the settings tab like so:

Add an id to the form with the name: myForm tag like so

All good!!!

Now when you click on the Submit button of your form, it works! But we will just get an empty email and we do not know if it actually worked or not from our website.

To do that we will need to add a then...catch... block. So instead of


<script>
emailjs.sendForm("YOUR_SERVICE_ID", "YOUR_TEMPLATE_ID", "#myForm")
</script>

Enter fullscreen mode Exit fullscreen mode

we will have this:


<script>
      // listen to the form submission
      document
        .getElementById("myForm")
        .addEventListener("submit", function (event) {
          event.preventDefault();

          const serviceID = "service_b4qmiqc";
          const templateID = "template_fv38whr";

          // send the email here
          emailjs.sendForm(serviceID, templateID, this).then(
            (response) => {
              console.log("SUCCESS!", response.status, response.text);
              alert("SUCCESS!");
            },
            (error) => {
              console.log("FAILED...", error);
              alert("FAILED...", error);
            }
          );
        });
    </script>

Enter fullscreen mode Exit fullscreen mode

In the code above, we just listen to when the form is submited and call the emailjs.sendForm() function. We now get a feedback message in our console and an alert feedback too.

It been a lot of work, let's test our hard work.

Testing

EmailJs In Action (GIF)

Javascript send form to email

EmailJs In Action (JPEG)

Email Received

YAAAhhhh, It works!!!

Javascript send form to email

Congratulations on your reaching this feet!!!

Conclusion

The purpose of this tutorial was to introduce EmailJs to you especially if you are a frontend developer with no backend knowledge in handling emails, you are looking for an easier way to be contactable via your website or you are just starting out in web development.

So we looked at a general overview of EmailJS, how to setup an account, create Email Services and templetes. Finally, we saw how to integrate it into your code if it is written on plain JavaScript. In the end, it was successful. I hope you had fun!

All Code Are Here

Next, I will be showing those who use React how this can be implemented. Until then, feel free to keep in touch.

Can form data be sent via JavaScript?

HTML forms can send an HTTP request declaratively. But forms can also prepare an HTTP request to send via JavaScript, for example via XMLHttpRequest .

Can I send HTML form data to email?

There is no feature in HTML to send the form submission directly to an email address. What about “mailto” ? Using mailto: You can set the action field of the form as 'mailto'. In this case, the web browser invokes the email client to send the form submission to the email address specified.

How do you create a form in HTML and send it to email?

Method 2: Create an Email Send Form Using PHP (Advanced).
Step 1: Use PHP to create a page. For this step, you'll need to have access to your website's cPanel on your hosting platform. ... .
Step 2: Make the form using code. In this step, you'll write the code to create the form. ... .
Step 3: Make the form send an email..