Send Emails in your React JS App with SMTP Express
Tags: react, howto, smtp
Published: 2024-05-04 08:02:05


## Table of Contents
- [Introduction](#intro)
- [Prerequisites](#prerequisites)
- [What is SMTP Express](#what)
- [Project Setup](#project-setup)
- [Creating the Email Form Component](#creating-emailForm)
- [Installing SMTP Express SDK](#installing-smtp)
- [API Key Integration] (#apiKey)
- [Handling Form Submission](#formSubmission)
- [Testing the Email Functionality](#testing)
- [Conclusion](#conclusion)

<a id="intro"></a>
## Introduction
Sending emails remains a pivotal feature in modern web applications, providing users with essential feedback on their data interactions. Traditionally, backend systems have shouldered the responsibility of managing email dispatch(delivery). However, the emergence of SMTP Express introduces a game-changing approach, allowing frontend applications to send emails directly, bypassing the need for complex backend setups.

In this article, we embark on an exploration of how to seamlessly integrate SMTP Express into React JS applications, transforming the email-sending experience.

Without further ado, let's plunge into the intricacies of harnessing SMTP Express to streamline email transmission in our React JS projects. 

<a id="prerequisites"></a>
## Prerequisites
This article assumes that you at least know the basics of working with react forms. You do not have to be an expert to follow along. 

<a id="what"></a>
## What is SMTP Express

![SMTP Cover Picture](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/evliguo0j8djod1f1j8o.png)

At its core, SMTP Express is an email delivery service that allows developers send emails directly from their projects without needing a backend server. 

<a id="project-setup"></a>
## Project Setup

To initiate our project setup, the first step involves registering with [SMTP Express](https://smtpexpress.com/).

Once registered, you'll gain access to a dashboard similar to the one shown below:

![Project Dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gxiga4rblcboyvo0yyqw.png)

If you're new to SMTP Express, your projects list will be empty.

Now you'll have to click on the `New Project` button to create a new Project, you will be navigated to the `Create New Project` page below


![Create New Project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6qikt22s703anhgunp6u.png)

It is important to note that the `Project Name` field is required, and in this write-up, I will name it **_smtp-article-example-demo_**

Next step requires you to click on the toggle switch that reads `I do not have an smtp server`. 
After toggling the `I do not have an SMTP server` switch, you'll notice that the User Interface(UI) transforms to something like this:


![Create New Project after toggling Switch](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9b7amjyf02fjtjqeg5rf.png)

Next, we'll click on `Create Project`, and SMTP Express will handle setting up our project on the server.

Afterwards, we're redirected to the dashboard, where we see our list of projects. If we have existing projects, the newly created one in our case **_smtp-article-example-demo_** will appear at the top alongside them. If it's our first project, it will appear alone on the dashboard 

Here's what my current Project Dashboard looks like at the moment:


![Current Projects Dashboard ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/21x159sogjtd5qrlhpm1.png)

Hooray! 🎊🎉 Our project setup on the SMTP Express Platform is now complete.


<a id="creating-emailForm"></a>
## Creating Email Form

Create a basic react project and add the following lines of code:

```react
import { useState } from "react";
import "./App.css";

function App() {
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState("");
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setLoading(true);
    if (!email || !message) {
      setLoading(false);
      return;
    }
    console.table({ email, message });
    setLoading(false);
  };

  return (
    <div className="app">
      <h2 className="app">Email Sending Form</h2>
      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="emailInput">Email:</label> <br />
          <input
            id="emailInput"
            type="email"
            required
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          ></input>
        </div>

        <div>
          <label htmlFor="message">Message:</label> <br />
          <textarea
            id="message"
            cols={30}
            rows={10}
            required
            value={message}
            onChange={(e) => setMessage(e.target.value)}
          ></textarea>
        </div>

        <button>{loading ? "Loading..." : "Send Email 🚀"}</button>
      </form>
    </div>
  );
}

export default App;

```

The Style for the form are as follows:

``` css
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.app {
  display: grid;
  place-items: center;
}

.app h2 {
  font-size: 2rem;
  margin: 1.5rem 0;
}

.app > form {
  width: 35%;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  padding: 1rem;
  border-radius: 0.5rem;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  background-color: white;
}

@media screen and (max-width: 768px) {
  .app > form {
    width: 80%;
  }
}

label {
  font-size: 1.25rem;
  font-weight: 600;
}

.app > form > div > input,
.app > form > div > textarea {
  margin-top: 1rem;
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 0.25rem;
}

.app > form > button {
  margin-top: 1rem;
  width: 100%;
  padding: 0.5rem;
  border: none;
  border-radius: 0.25rem;
  background-color: #007bff;
  color: white;
  font-size: 1.2rem;
  font-weight: 600;
  cursor: pointer;
}

.app > form > button:hover {
  background-color: #0056b3;
}

```
After adding the styles, we should have something like this on our web page:


![Web UI form](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x2kwwdo255oc0djzyeje.png)

Now that we have our UI all set up, let's move on and see how to integrate SMTP Express into our React Application.

<a id="installing-smtp"></a>
## Installing SMTP Express SDK

Here comes the exciting part! We'll integrate SMTP Express into our React JS project.

To install SMTP Express SDK, we need to run the following command in any terminal of our choice

```bash
npm install smtpexpress
```
The code above adds the SMTP library to our React JS Project. 

<a id="apiKey"></a>
## API Key Integration
To begin, create a new file using either JavaScript or TypeScript. Let's name this file smtp.js if you're using JavaScript, or smtp.ts if you're using TypeScript

Now add the following code to it

```js
import { createClient } from "smtpexpress"

export const smtpexpressClient = createClient({
  projectId: "<INSERT_PROJECT_ID>",
  projectSecret: "<INSERT_PROJECT_SECRET>"
});
```
To get your `Project Id` and `Project Secret` you have to navigate to your project dashboard 


![Project Dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rptht6ov81n2md6mh76w.png)

To get a `Project Secret`, you would need to generate it. 
Click on the `Click to create a new secret link`, afterwards you will be navigated to the `create-secret` page


![Project Secret](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e6xgwal1khq1xrfl2bbl.png)

Next, you click on the `Create New` button to generate a product secret. A slider appears on the right of the page with the following details: 


![Project Secret Slider](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/plb7rumuztcaewsy3grw.png)

Let's name our secret `Default Secret`; for now, we'll use `localhost` as our domain. Later on, you can update the domain to reflect where your project will be hosted, such as Netlify or Vercel.

When the `Create Secret` button is clicked, it generates a project secret.

When you obtain the Project ID and Secret tokens, please insert them into the smtp.js or smtp.ts file you created earlier.

Now that we have obtained our Project ID and Secret, let's understand how to utilize SMTP to send emails to our users.

<a id="formSubmission"></a>
## Handling Form Submission
 
In the previous section, we successfully crafted a dynamic form component, equipped with the `email` and `message` input fields and an onSubmit handler. 

We will have to update or redefine the onSubmit handler which is the handleSubmit function in our case. 
Here's how the code looks like now:

```js
  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setLoading(true);
    if (!email || !message) {
      setLoading(false);
      return;
    }
    console.table({ email, message });
    
    try {
      // Sending an email using SMTP
      await smtpexpressClient.sendApi.sendMail({
        // Subject of the email
        subject: "Confirmation: Email sent successfully",
        // Body of the email
        message: `<h2>${message}</h2>`,
        // Sender's details
        sender: {
          // Sender's name
          name: "SMTP Article by DevYoma",
          // Sender's email address
          email: "<PROJECT_SENDERS_EMAIL_ADDRESS>",
        },
        // Recipient's details
        recipients: {
          // Recipient's email address (obtained from the form)
          email: email,
        },
      });

      // Notify user of successful submission
      alert("Please check your email to view the sent message.");
      setLoading(false);

      setEmail("");
      setMessage("");
    } catch (error) {
      // Notify user if an error occurs during submission
      alert("Oops! Something went wrong. Please try again later.");
      // You can console.log the error to know what went wrong
      console.log(error);
      setLoading(false);
    }
    
  };
```

To obtain your `PROJECT_SENDERS_EMAIL_ADDRESS`, navigate to the settings page of your project. Here, you'll find a user interface similar to the one depicted below:


![Sender Email](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r39ti988tvn8c8jozwql.png)

Copy the provided code snippet, which contains your `PROJECTS_SENDERS_EMAIL_ADDRESS`, and replace the corresponding placeholder in the handleSubmit function with this value. This step ensures that your email sender address is correctly configured for SMTP integration.

<a id="testing"></a>
## Testing the Email Functionality
Now, let's test our email functionality right on our localhost.


![Populated Form](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oehl83qexl9mywxrl7xb.png)

Onclick of the `Send Email` button, you should get an alert saying `Please check your email to view the sent message.`. You would see this if you correctly configured the project. 

![Confirmation Email](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/juqml2kh16osiyhzslzc.png)


<a id="conclusion"></a>
## Conclusion

Throughout this article, we've explored the integration of SMTP Express into React JS applications, streamlining the process of sending emails. I'm delighted that you've followed along to this point, and I encourage you not only to absorb the content but also to implement and apply what you've learned here. Happy coding!

For a hands-on experience, clone the code and follow the detailed setup instructions to see it in action. Explore additional usage instructions in the accompanying GitHub repository: [here](https://github.com/DevYoma/react-smtp-express-article)

Lastly, if you've found value in this article, I invite you to consider sharing it with your peers who may also benefit from its insights.

What are your thoughts on the topic of Sending Emails with SMTP? Feel free to share your thoughts in the comments section below.