DEV Community

Cover image for Contact Form with Emailjs - Plain JavaScript
NJOKU SAMSON EBERE
NJOKU SAMSON EBERE

Posted on

Contact Form with Emailjs - Plain JavaScript

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.

Let's Get Started

Create and Setup a free Account

You should now be in your dashboard like so:
emailjs dashboard

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

  • Click on Add Email Service:
    Add Email Service

  • Select Gmail from the dialogue box:
    Gmail

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

  • Click on Connect Account just below the Service ID.
    Connect Account

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

  • Check all boxes and Continue

Check all boxes

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

connection is successful with confirmation message

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

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

Create Service Button

You should now have a new service added like so:
a new service added

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

  • Click on Create New Template Create New Template

You will now have the template screen like so:
template screen

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:

email content

Click on Save
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.
Moving On To The Next

JavaScript

Starter Project

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


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

Enter fullscreen mode Exit fullscreen mode

After setting it up in your local machine, you should have the following screen:
Starter Project 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:

Image description

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

YOUR_SERVICE_ID

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

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


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

EmailJs In Action

EmailJs In Action (JPEG)

Image description

Email Received

Email Received

YAAAhhhh, It works!!!

Victory

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.

Discussion (8)

Collapse
marizoo profile image
Marizoo

Thank You so much Njoku! You've put so much effort into this. I truly appreciate it. I was having problems but it's all good now. :-)

Collapse
ebereplenty profile image
NJOKU SAMSON EBERE Author

I am happy I could be of help. Thank you for your this feedback 😊

Collapse
ebereplenty profile image
NJOKU SAMSON EBERE Author

Thank you. Will check it out

Collapse
patik123 profile image
Patrick • Edited on

Never hear for this email service. Nice.

Collapse
xr0master profile image
Sergey Khomushin

Great article, thank you.

Collapse
ebereplenty profile image
NJOKU SAMSON EBERE Author

Wow... I happy to keep writing

Collapse
shajib729 profile image
Mohammed Sajidul Islam

I want to send a message like otp code or any verification email from node js directly. I don't want to send it in front end. Can i do this using emailjs.
Please reply....