DEV Community

Cover image for Send Emails in your React JS App with SMTP Express
Emore Ogheneyoma Lawrence
Emore Ogheneyoma Lawrence

Posted on • Updated on

Send Emails in your React JS App with SMTP Express

Table of Contents

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.

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.

What is SMTP Express

SMTP Cover Picture

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

Project Setup

To initiate our project setup, the first step involves registering with SMTP Express.

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

Project Dashboard

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

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

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

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

Creating Email Form

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



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;



Enter fullscreen mode Exit fullscreen mode

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



Enter fullscreen mode Exit fullscreen mode

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

Web UI form

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

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



npm install smtpexpress


Enter fullscreen mode Exit fullscreen mode

The code above adds the SMTP library to our React JS Project.

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



import { createClient } from "smtpexpress"

export const smtpexpressClient = createClient({
  projectId: "<INSERT_PROJECT_ID>",
  projectSecret: "<INSERT_PROJECT_SECRET>"
});


Enter fullscreen mode Exit fullscreen mode

To get your Project Id and Project Secret you have to navigate to your project dashboard

Project Dashboard

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

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

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.

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:



  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);
    }

  };


Enter fullscreen mode Exit fullscreen mode

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

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.

Testing the Email Functionality

Now, let's test our email functionality right on our localhost.

Populated Form

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

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

If you want to learn how to send Calendar Invites using SMTP Express, I have an article about it here

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.

Top comments (2)

Collapse
 
abhijeetc18 profile image
Abhijeet chougule

mails are going to in spam how do I prevent it?

Collapse
 
devyoma profile image
Emore Ogheneyoma Lawrence

Hi Abhijeet, this is new to me, I'll get in touch with creator of the package and relay this.
Try to avoid spam trigger words like "free", "urgent", "make money" or excessive exclamation marks if you're using any.