Contact Form with Emailjs - Plain JavaScript
Tags: react, javascript, email, contact
Published: 2021-10-29 12:01:48

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](https://www.emailjs.com/) was created. **It is also free.**

[Emailjs](https://www.emailjs.com/) 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](https://www.emailjs.com/pricing/).

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.

![Let's Get Started](https://media.giphy.com/media/CjmvTCZf2U3p09Cn0h/giphy.gif)

## Create and Setup a free Account
* Go to the [signup page](https://dashboard.emailjs.com/sign-up) and create an account.

> You should now be in your dashboard like so:
![emailjs dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qrhfz8m9pbx77szqi8hc.JPG)

### Add a new Email Service
Email Service could be **Personal** or **Transactional**. You can read more on that [here](https://www.emailjs.com/docs/tutorial/adding-email-service/).

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**:
![Email Services](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8t5nh4k9ybz7lts6n5iu.JPG)

* Click on **Add Email Service**:
![Add Email Service](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q4keqe8pb4eocv2j7g0u.JPG)

* Select **Gmail** from the dialogue box:
![Gmail](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ukp1vgjvzhhu0y3qfyz.JPG)

* You can now see your **Service ID** in the screen that follows
* Click on **Connect Account** just below the **Service ID**.
![Connect Account](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8bl5clrmjflyek2xqcmv.JPG)

> 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

![gmail authorization screen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ihhr431cuqbljfj29bcz.JPG)

* Check all boxes and **Continue**

![Check all boxes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cwjf4zgqwcm178jy5wdk.JPG)

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

![connection is successful with confirmation message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iqh59dn1zovoibzv1oj5.JPG)

*You can always come back here to disconnect*

I also got an email to confirm my connection to Emailjs:
![email to confirm my connection to Emailjs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xjxa3ruy17fmyydhlp8t.JPG)

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

![Create Service Button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/411qufwa4by9ys3xwb2h.JPG)

> You should now have a new service added like so:
![a new service added](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/191kcqdlrd254twq03hd.JPG)

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

![Email Templates Link](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mmk94hczxykdkbui3ptg.JPG)

* Click on **Create New Template**
![Create New Template](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g0rs3ycb2cuxegvk5nlz.JPG)

You will now have the template screen like so:
![template screen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/73ypzik9xvmx4b9thgng.JPG)

> 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:

```javascript

{{message}}

{{name}}
{{email}}

```
My screen now looks like this:

![email content](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/832u6rsds39jn05c3ze8.JPG)

Click on **Save**
![Click on Save](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mvhki2vhm0xtdb3gwyyg.JPG)

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.
![Moving On To The Next](https://media.giphy.com/media/8Yam7VjgXfG77Pkebq/giphy.gif)

## JavaScript
### Starter Project
Get the starter code [here](https://github.com/EBEREGIT/js-emailjs/tree/starter-code) or just create a project with a file: *index.html* and add the following code:

```html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <!-- bootstrap CSS -->
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
      integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
      crossorigin="anonymous"
    />
    <title>JavaScript Emailjs</title>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col align-self-center">
          <h1 class="text-center">Email - JavaScript Contact Form</h1>
          <!-- contact form -->
          <form id="myForm">
            <!-- name -->
            <div class="form-group">
              <label for="name">Name</label>
              <input
                type="name"
                name="name"
                class="form-control"
                id="name"
                placeholder="enter your name"
              />
            </div>

            <!-- email -->
            <div class="form-group">
              <label for="email">Email address</label>
              <input
                type="email"
                name="email"
                class="form-control"
                id="email"
                placeholder="enter your email"
              />
            </div>

            <!-- subject -->
            <div class="form-group">
              <label for="subject">Subject</label>
              <input
                type="text"
                name="subject"
                class="form-control"
                id="subject"
                placeholder="enter email subject"
              />
            </div>

            <div class="form-group">
              <label for="message">Message</label>
              <textarea class="form-control" id="message" name="message" rows="5"></textarea>
            </div>

            <button type="submit" class="btn btn-primary">Submit</button>
          </form>
        </div>
      </div>
    </div>

    <!-- bootstrap js -->
    <script
      src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
      integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
      crossorigin="anonymous"
    ></script>

</body>
</html>

```

After setting it up in your local machine, you should have the following screen:
![Starter Project Screen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1p2bjy53253y11ln8nym.JPG)

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

* Install EmailJs by adding the following script at the bottom

```Javascript

    <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>

```
**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:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1rbbfhxp5gbeiefh0q1w.JPG)

Your USER_ID is down below under the **API Keys**

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

```javascript

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

```
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

![YOUR_SERVICE_ID](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fn0w746c5fmsdokjabr7.JPG)

> 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:

![YOUR_TEMPLATE_ID](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dw3cr4xy0gwdbl9h5fsr.JPG)

> Add an ``id`` to the ``form`` with the name: **myForm** tag like so ``<form id="myForm">``

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  

```javascript

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

```
we will have this:

```javascript

<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>

```
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)
![EmailJs In Action](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2kpt0wp64576d13e1vyj.gif)

### EmailJs In Action (JPEG)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sygcj06upqiknt7bmvvz.JPG)

### Email Received
![Email Received](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3lzhdtjmv4pzjdmpqsdp.JPG)

YAAAhhhh, It works!!!

![Victory](https://media.giphy.com/media/zBhZiVNNQjfTG/giphy.gif)

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](https://github.com/EBEREGIT/js-emailjs)

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