DEV Community

Blujay0
Blujay0

Posted on • Edited on

📧 Send Emails using React Forms

NOTE: emailjs-com is deprecated. Use the current SDK which can be found here 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

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

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

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

4. add-new-service

On the following window, press Connect Account:

5. Connect-Account

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

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

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

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>
Enter fullscreen mode Exit fullscreen mode

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

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));
  }
Enter fullscreen mode Exit fullscreen mode

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

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

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

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

Top comments (2)

Collapse
 
xr0master profile image
Sergey Khomushin

Please note that the emailjs-com package has long been deprecated.

Collapse
 
blujay0 profile image
Blujay0

thank you @xr0master, I've updated my post to reflect the deprecation!