React Send Email Guide

(Free And Without Backend)

React Send Email

We all know that React's primary purpose is to be running in browsers. Because of that, it's super powerful but also has quite a few limitations. For example, being client-side only, it can't do certain things that we would take for granted on the server-side. A good example would be sending emails. As all the client code is public, you wouldn't want to expose your mail server credentials to the whole world.

So the question is, how to send emails from React without a backend? Luckily, this guide answers it perfectly.

P.S. If you want to know how to send form data (such as contact form fields), you can read the React Contact Form guide.

Create the email function inside of React App

You'll send the email on that function. We’ll need to get two arguments for it to work: endpoint URL and "data." Then, a simple POST request and returning the state with the response of that request. We'll be using react hooks, but the example is straightforward to port to the class components. See the sample code.

1import { useState } from "react";
2
3const UseEmail = (endpointUrl) => {
4  const [submitted, setSubmitted] = useState(false);
5  const [loading, setLoading] = useState(false);
6  const [error, setError] = useState();
7
8  const sendEmail = (data) => {
9    setLoading(true);
10    setSubmitted(false);
11    setError(undefined);
12
13    fetch(endpointUrl, {
14      method: "POST",
15      headers: {
16        Accept: "application/json",
17        "Content-Type": "application/json",
18      },
19      body: JSON.stringify(data),
20    })
21      .then((response) => {
22        // Endpoint thinks that it's likely a spam/bot request, you need to change "spam protection mode" to "never" in HeroTofu forms
23        if (response.status === 422) {
24          throw new Error("Are you robot?");
25        }
26
27        if (response.status !== 200) {
28          throw new Error(`${response.statusText} (${response.status})`);
29        }
30
31        return response.json();
32      })
33      .then(() => {
34        setSubmitted(true);
35        setLoading(false);
36      })
37      .catch((err) => {
38        setError(err.toString())
39        setLoading(false);
40      });
41  };
42
43  return {
44    submitted, loading, error, sendEmail
45  }
46};
47
48export default UseEmail;

Signup for the free HeroTofu account

To create an account, go to herotofu.com . It is capable of handling all the complex email sending work. You can take the 14-day free trial and then leave it in the free forever plan. It's usually more than enough for small websites.

The registration is easy. After filling in the primary fields, you should receive an email confirmation.

Herotofu signup

Create a new backend, set your email, spam protection

Go to app.herotofu.com/forms to make your first form after you have confirmed your email address. In this case, the form will function as our API backend/endpoint. Attach your preferred email address where you'd like to receive your data submits. Be sure to select spam protection as "never." You'll be sending API requests yourself, so they shouldn't ever be detected as spam by HeroTofu.

Remember to copy the endpoint URL once you hit submit.

Herotofu Forms List

Add component into your app, pass some data

The last step is implementation. Call your created function with the endpoint URL and actual data. HeroTofu will forward that data to your email.

1// Your imports...
2import UseEmail from "./UseEmail";
3
4// Example component
5function App() {
6  // You don't need to manage state by yourself
7  // use the variables below
8  const {
9    loading,
10    submitted,
11    error,
12    sendEmail
13  } = UseEmail(YOUR_FORM_ENDPOINT);
14
15  const sendExample = () => {
16    // Can be any data, static and dynamic
17    sendEmail({
18      example_user: "user@example.com",
19      example_data: new Date().toISOString(),
20    });
21  };
22
23  return (
24    <div className="App">
25      <header className="App-header">
26        <img src={logo} className="App-logo" alt="logo" />
27        <div style={{ margin: "1rem 0", fontSize: '2rem' }}>
28          { submitted && 'Done, email was sent!' }
29          { error ? `Unexpected error: ${error}` : null}
30          { loading && 'Email is being sent now...' }
31        </div>
32        <div style={{ margin: "1rem 0" }}>
33          <button onClick={sendExample}>Send test data</button>
34        </div>
35      </header>
36    </div>
37  );
38}

That's it!

You can now send emails from your React application. All without the burden of the server/backend code.


Related questions

How do I send form data to an email in React?

It's doable via HeroTofu; check out the React Contact Form guide guide.

How do I create a contact form in React JS?

This guide has an example of the ready-to-use contact form.

How do I send an email in the Next JS?

As it uses the React framework under the hood, the process is identical to this guide.

Can I use Nodemailer in React?

Unfortunately, no. Nodemailer is the backend-only library.

How do I send an email with Sendgrid and Reactjs?

For either of these, you would need to use the backend. This process could expose your credentials which can raise big security concerns. You don't need any email provider when using HeroTofu.

How do you use EmailJS?

EmailJS is a fantastic email service that also lets you send emails from the frontend. Yet, if you operate mainly with form-like data structures, HeroTofu would fit a bit better.

 
React Email Endpoint -- Start NowFree and Paid plans