DEV Community

Dalibor Belic
Dalibor Belic

Posted on • Updated on

How to send emails from a form in React (EmailJS)

Intro

This post will guide you through the process of creating a form and functionality in ReactJS (with hooks) that will enable us to send emails. We will use a third-party service called EmailJS.

EmailJS in a nutshell

Send emails using client-side technologies only. No server required.

  1. Pick one of the supported email services
  2. Create an email template
  3. Use JS library to trigger an email

Setup EmailJS

Let's first create a free account.
Now, we'll do step 1. from the intro: we will pick Gmail as our email service.

alt text On 'Email Services' tab. After clicking on the 'Add New Service' button you should be seeing something similar to the photo above. Click on Gmail (this is what we'll use in this case).
alt text
To connect the service with your Gmail account click on the 'Connect Account' button. Also, remember your Service ID because we'll need it later. Finally, click on the 'Create Service' and check your inbox to see if you got the test email.
Got it? Awesome!

In the intro Step 2. says create a template. Let's do that now. Go to the 'Email Template' tab on the side menu and click on the 'Create New Template' button. For testing purposes, we will use this default one. A caveat, the variables in double curly brackets are dynamic variables that will be replaced with the data we'll provide in the method emailjs.send, in our case, in React. Click 'Save' and we're good to proceed.

Congrats, part one is done!πŸ₯³


React

I assume you know how to and have created a react app. If not, check this out.

Let's install emailjs package.
npm i emailjs-com

Now, we import it (grab the User ID).

import './App.css';
import { useState } from 'react';
import { send } from 'emailjs-com';

function App() {
  return (
    <div className="App">
      ...
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Now let's create our form inside div.App

<form onSubmit={onSubmit}>
  <input
    type='text'
    name='from_name'
    placeholder='from name'
    value={toSend.from_name}
    onChange={handleChange}
  />
  <input
    type='text'
    name='to_name'
    placeholder='to name'
    value={toSend.to_name}
    onChange={handleChange}
  />
  <input
    type='text'
    name='message'
    placeholder='Your message'
    value={toSend.message}
    onChange={handleChange}
  />
  <input
    type='text'
    name='reply_to'
    placeholder='Your email'
    value={toSend.reply_to}
    onChange={handleChange}
  />
  <button type='submit'>Submit<button/>
</form>
Enter fullscreen mode Exit fullscreen mode

Awesome, let's continue. Now, your App component should look like this now:

...

function App() {
  const [toSend, setToSend] = useState({
    from_name: '',
    to_name: '',
    message: '',
    reply_to: '',
  });

  const onSubmit = (e) => {
    e.preventDefault();
    {/* --- METHOD TO SEND THE MAIL --- */}
  };

  const handleChange = (e) => {
    setToSend({ ...toSend, [e.target.name]: e.target.value });
  };

  return (
    <div className='App'>
      {/* --- FORM --- */}
    </div>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

You see, we used useState() Hook that lets you add React state to function components. We initialized the state with the 'toSend' object with the same instance names as the dynamic ones we have in the emailjs template. We also created two methods are for manipulating form data. handleChange to update the state, and onSubmit to handle the submission; to send data via emailjs.send method that we'll implement right away.

This is how onSubmit should look like:

const onSubmit = (e) => {
    e.preventDefault();
    send(
      'SERVICE ID',
      'TEMPLATE ID',
      toSend,
      'User ID'
    )
      .then((response) => {
        console.log('SUCCESS!', response.status, response.text);
      })
      .catch((err) => {
        console.log('FAILED...', err);
      });
  };
Enter fullscreen mode Exit fullscreen mode

Please add your unique IDs required in the send method that you can find on emailjs dashboard.


Okay, here goes nothing...

Run that app (npm start).
Fill the form and click submit.
Check your Gmail inbox.
Got it?

CONGRATS! You rock! πŸ₯³πŸŽŠ


I hope you find my first post useful! Any feedback is greatly appreciated!

Thank You!
Dalibor

Top comments (18)

Collapse
 
boly38 profile image
Brice

to complete about dep: emailjs free plan it's 200 emails per month
there is also sendgrid service (100 mail per day) sendgrid.com/pricing/
there is maybe (ton of) other free providers. Thanks for this post πŸ‘

Collapse
 
daliboru profile image
Dalibor Belic

Thanks for sharing, and you're welcome!

Collapse
 
julienp17 profile image
Julien Pause

You have a small typo in the second code preview of the React part.
It should be </button> instead of <button/> (the slash is misplaced).
Great article though! It helped me for the contact page of my (future) website. πŸ˜‰
EmailJS also offer their own implementation for React.

Collapse
 
nodedev profile image
Angel Rodriguez

For those having issues setting up your .env, here's a good article (only if you've used Vite to set up your React app, not sure about CRA).

Mastering Environment Variables in Vite

Collapse
 
sylwiavargas profile image
Sylwia Vargas

That’s fantastic! I’ll share your blog post with my students ✨

Collapse
 
daliboru profile image
Dalibor Belic

Awesome! This means a lot! :)

Collapse
 
amrindra profile image
Amrindra

Hi there, do you happen to know if it works with .env? I tried to put my userID and serviceID in the .env file, but for some reasons it doesn't work. That's why I am wondering if emailjs work with .env file. Thank you.

Collapse
 
vladav profile image
vladaV

Hi, did you find solution for .env and EmailJS? I have a same problem, and didn't find any workable solution.

Collapse
 
toluc profile image
Toluwanimi Adeyemo

Thanks for the tutorial, it's helpful.
Pls, how do I go about sending file attachments with emailjs and react.

Collapse
 
huydzzz profile image
PΖ‘ HΓ­p

you are kind

Collapse
 
huydzzz profile image
PΖ‘ HΓ­p

this mean a lot to me

Collapse
 
lucasfrutig0 profile image
lucasfrutig0

Niiiice

Collapse
 
daliboru profile image
Dalibor Belic

Tnx!

Collapse
 
hrqmonteiro profile image
Henrique Monteiro

Yeah, literally doesn't fucking work. I press the Submit button and nothing happens.

Collapse
 
hardikchopra profile image
Hardik Chopra

Thanks for the tutorial πŸ‘
Working fine for me. Btw, is there any other email service better than emailJS?

Collapse
 
officialrj18 profile image
Rajendra Arya

Thanks man, it was really helpful,
we can also do this from formsubmit, its also a great and easy tool for form submission.

Collapse
 
akwasin profile image
akwasin

Worked like a charm. Thanks for this post.

Collapse
 
timjini profile image
Timjini

amazing, I will just mention again the typo :)))