Send Email in React Without a Backend.

📅October 13, 2020

🕒6 minute read

🏷

react

email

Email sending in static websites can be distressing at times, even more so when you don't have experience. This post is for anyone seeking for a straightforward way to JUST SEND THAT EMAIL on your website, without a cumbersome procedure.

There's an awesome email service named Enformed which grants you email sending without the need of a backend service or some nasty PHP script. Before starting, sign up on their page (it'll take you 20 seconds).

Supposing you have some sort of form already set up in your React app, for example:

class Form extends React.Component {
  state = {
    name: "",
    text: "",
  };

  render() {
    const { name, text } = this.state;

    return (
      <form>
        <div>
          <label>Name</label>
          <input
            type="text"
            value={name}
            onChange={(e) => this.setState({ name: e.target.value })}
          />
        </div>

        <div>
          <label>Text</label>
          <input
            type="text"
            value={text}
            onChange={(e) => this.setState({ text: e.target.value })}
          />
        </div>

        <button>Send Email</button>
      </form>
    );
  }
}

First, make sure you have an onClick handler for your form submit button.

<button onClick={this.handleSubmit}>Send Email</button>

Now, for the actual email sending we're going to use Enformed's API. Copy your Enformed token from here. We'll be using JavaScript's fetch API to send the request.

handleSubmit = (e) => {
  e.preventDefault(); // Never 4get

  const emailToken = "tom-misch";
  const { name, text } = this.state; // data you want to send

  fetch(`https://www.enformed.io/${emailToken}/`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify({ name, text }),
  })
    .then((response) => response.json())
    .then((data) => console.log(data))
    .catch((err) => console.log(err));
};

Simple, right? Now spam that send button 👊 (not too much though). Later.