📧 Send Emails using React Forms
Tags: tutorial, frontend, react, beginners
Published: 2023-07-28 10:45:22

> NOTE: `emailjs-com` is deprecated. Use the current SDK which can be found [here](https://www.npmjs.com/package/emailjs) or install using `npm install @emailjs/browser`!

# Introduction
In this article, I will cover how to send emails from React Forms created in an example web application, using a free JavaScript library known as **EmailJS**.

## Create Your React Form
Begin by creating a 'Contact Us' component and inside, we will have our form. For the purpose of this article, I have created a simple form with basic styling:

![1. ContactUsForm](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ub50drb51neg8z0s691d.png)

## Integrate EmailJS into the application
First, in the terminal of the code editor, `cd` to the /client directory of the app, and install EmailJS with the following command: `npm i emailjs-com`.

![2. npm-install-emailjs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/83sh97dtoyuqddsvaw3b.png)

Next, we import *emailjs* into our `<ContactUs />` component like so:
`import emailjs from 'emailjs-com'`

Before we go further, let's create the free EmailJS account!

## Create a Free EmailJS Account + Email Service
Go ahead to the [EmailJS](https://www.emailjs.com) website and signup for a free account. They allow up to 200 emails per month for free.
Once you successfully signup and login, you will be brought to this page:

![3. EmailJS-firstpage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4v521aenrno41spugjca.png)

Click on the **Add New Service** button near the top and choose the email provider of your choice:

![4. add-new-service](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2yvrz2klxb5zaszvl473.png)

On the following window, press **Connect Account**:

![5. Connect-Account](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rjzjtx3ekmkpeg7gs065.png)

A window will pop-up that will ask you which Gmail account you wish to choose to continue with EmailJS. Then, you need to allow EmailJS a certain amount of access to your Google Account (this is standard procedure).

When that's done, you will be able to finally press the **Create Service** button and you should see a new service added on your **Email Services** page:

![7. service-id-added](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nedrrrfyfcafdz54khpz.png)

## Create an Email Template
Now we need to create a template that our email will follow. The navigation bar on the left has an option for *Email Templates*, press it and you should be taken to the **Email Templates** page:

![8. email-templates-page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/degxt41g2duswpn5v8c4.png)

Notice the **Create New Template** button near the top. Press it and you will be taken to a form page where you can fill out the necessary information to create your template:

![9. template-form-page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/45835nkeuvz3mpvd9sot.png)

Now, notice the `{{to_name}}`, `{{from_name}}`,  `{{message}}`, and `{{reply_to}}` on the forms. To know what we need to place in these double curly braces, we need to look at our code for the form:

```
      <form style={{marginLeft: "100px"}} onSubmit={sendEmail}>
        <h1 style={{fontSize: "50px"}}>Contact Us</h1>
        <div>
          <label style={{fontSize: "25px"}}>Name: </label>
          <input type='text' name='user_name' style={{fontSize: "25px"}}/>        
        </div>
        <br />
        <div>
          <label style={{fontSize: "25px"}}>Email: </label>
          <input type='email' name='user_email' style={{fontSize: "25px"}}/>
        </div>
        <br />
        <div>
          <label style={{fontSize: "25px"}}>Message: </label>
          <br />
          <textarea name='user_message' rows='6' cols="50" style={{fontSize: "25px"}}/>
        </div>
        <input type='submit' value='Send' style={{backgroundColor: "#87CEEB", color: "black", padding: "8px 32px", margin: "4px 2px", fontSize: "20px"}}/>
      </form>
```

For each `<input/>` element in the form, note the `name` attributes and their values. The values of the `name` attributes are what we are going to pass into double curly braces on our email template form. For example, the value of the `name` attribute of the `<textarea/>` element is `user_message` so that is what we will pass inside the curly brace of `{{message}}` in our email template form.

Going by that logic, we can replace `{{from_name}}` plus the *From Name* box with `{{user_name}}`, `{{message}}` with `{{user_message}}`, and you can fill in the *From Email* box with `{{user_email}}`. The `{{to_name}}` can be left blank for our purposes and it will just render as blank space in the email once it is sent:

![10. filled-template-form](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f97414zslqu67a15jgju.png)

> NOTE: remember to put your email address in the *To Email* text field so you can receive the email(s) in the format set by your template. Obviously, you can change the email address later, based on who you want the automated messages to be sent to!

## Create a submit handler function for the form
Now that that is all setup, we need to create our submit handler for our form. We will need three things from EmailJS: the **Service ID**, **Template ID**, and your **Public or Private Key** that can be found in your `Account` page in your navigation bar.

In the `ContactUs` component, create the following submit handler:
```
const sendEmail = (e) => {
  e.preventDefault();
 
  emailjs.sendForm(
    "YOUR_SERVICE_ID", 
    "YOUR_TEMPLATE_ID", 
    e.target, 
    "PUBLIC_KEY"
    ).then(res => {
      console.log(res);
    }).catch( err=> console.log(err));
  }
```

And make sure to pass it to the `<form>` element as a value to the `onSubmit` attribute! You can see what I mean by looking at the <form> code from before.

## Test It Out!
Time to check if it works! 
Let's fill out the form with some dummy info and hit *Send*:

![11. fill-form-dummy-text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qlbph4vtub3p5nbkpw62.png)

... and success! You should have received an email with the contents in the format set by the template that you defined:

![12. success-receive-email](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l4bf8eac5o707prstqsb.png)


## Conclusion & Further Considerations
Email sending functionality is commonplace in web development. Most websites that you construct will be required to send automatic emails.

Now, we've only covered frontend email integration, but email integrations become very powerful when used on the server-side.

Just think of the multitude of use-cases for automated emails:
* update a customer on the shipping status of their order
* cart abandonment emails
* notifications about wishlisted products being on sale
* birthday emails
* event invitation emails
* welcome emails
* reward/loyalty point emails

...the list goes on and on...

And that's that! I hope you found this article useful and happy coding!

## Resources
* [WatchList](https://github.com/Blujay0/WatchList) - the git repo where you can find the example used in this article
* [EmailJS](https://www.emailjs.com)
* [Smtpjs](https://smtpjs.com) - a similar free library like EmailJS that you can use to send emails from JavaScript
* [React Documentation](https://react.dev/)
* [Article on some email automation examples](https://www.brevo.com/blog/email-automation-examples/)