Table of Contents
- Introduction
- Prerequisites
- What is SMTP Express
- Project Setup
- Creating the Email Form Component
- Installing SMTP Express SDK
- API Key Integration
- Handling Form Submission
- Testing the Email Functionality
- Preventing Abuse
- Conclusion
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
At its core, SMTP Express is an email delivery service that allows developers to send emails directly from their projects without needing a backend server. But we do much more than just basic email sending.
SMTP Express has evolved into a comprehensive business emailing suite that empowers developers and businesses with a complete email infrastructure. Beyond transactional emails, SMTP Express allows you to provision professional inboxes, collaborate seamlessly with team members on shared inboxes, and reach your audience effectively through its powerful Email Broadcast Platform.
Whether you're building a simple contact form or managing complex email workflows for your business, SMTP Express provides all the tools you need in one integrated platform.
Project Setup
To initiate our project setup, the first step involves registering with SMTPExpress.
Once registered, you'll gain access to a dashboard similar to the one shown below:
If you're new to SMTP Express, your projects list will be empty.
Click the New Project
button to open a modal where you can create a new project, as shown below.
We'll use SmtpExpress-demo as the project name for this example.
After clicking the Create Project
button, you'll be taken to the dashboard, which looks like this:
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;
The Style for the form are as follows:
* {
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:
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
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>"
});
Getting Your API Credentials
Once you’ve created a project, your Project ID, Project Secret, and Sender Address are all available right from the Overview section of your project dashboard.
Just copy the values and paste them into your smtp.js
or smtp.ts
file where indicated.
Now that your credentials are set up, let’s move on to setting up our environment variables.
Using Environment Variables
To keep things organized and secure, it's a good idea to store your credentials and config values in an .env
file. For this project, I’ve added the following variables to my .env.local
file:
VITE_SMTP_PROJECT_ID=your_project_id_here
VITE_SMTP_PROJECT_SECRET=your_project_secret_here
VITE_SMTP_PROJECT_SENDER_EMAIL=you@example.com
Then in your code, you can access them using import.meta.env
like so:
export const smtpexpressClient = createClient({
projectId: import.meta.env.VITE_SMTP_PROJECT_ID,
projectSecret: import.meta.env.VITE_SMTP_PROJECT_SECRET,
});
And when sending an email:
sender: {
name: "SMTPExpress Article Demo by DevYoma",
email: import.meta.env.VITE_SMTP_PROJECT_SENDER_EMAIL,
}
Now let's move on to Handling our form submission and successfuly sending our first email via SMTPExpress
Handling Form Submission
Back in the Creating the Email Form 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: `Contact form submission from ${email.split("@")[0]}`,
// Body of the email
message: `
<p><strong>Message from:</strong> ${email}</p>
<p><strong>Content:</strong></p>
<p>${message}</p>
`,
// Sender's details
sender: {
// Sender's name
name: "SMTPExpress Article Demo by DevYoma",
// Sender's email address
email: import.meta.env.VITE_SMTP_PROJECT_SENDER_EMAIL,
// email: "xxxxxxxxx" 👈put your Project Sender Address here
},
// Recipient's details
recipients: {
// Recipient's email address (obtained from the form)
email: email,
},
});
// Notify user of successful submission
toast.success("Please check your email to view the sent message.");
setLoading(false);
setEmail("");
setMessage("");
} catch (error) {
// Notify user if an error occurs during submission
toast.error("Oops! Something went wrong. Please try again later.");
console.log(error);
setLoading(false);
} finally {
setLoading(false);
}
};
Testing the Email Functionality
Now, let's test our email functionality right on our localhost.
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.
Preventing Abuse
When deploying your React app to production, you'll want to protect your SMTP Express credentials from unauthorised usage. SMTP Express provides custom project secrets that restrict API access to specific domains.
Creating a Custom Secret
In your SMTP Express dashboard, click on the Credentials
menu.
Click Create Secret
.This opens the secret creation panel on the side of the current UI you're on
Now we need to configure our Secret:
- Secret Name: Enter
Production Secret
- Authorised Origin: Leave this field empty for now. The cloned or forked GitHub repository should be hosted on Vercel, but do not set the Vercel domain as an authorised origin yet. We will test the functionality with and without the domain set as an authorised origin to show how it affects the project.
We would have 2 tests: One without setting the domain as an authorised origin, and one with the domain set as an authorised origin. The former would fail while the latter would succeed.
NB: localhost is by default an authorised origin.
Now we have 2 Project Secrets, and this is how our UI looks at the moment
Now let's test and see the Domain Restriction in action
Testing Domain Restriction
Update your .env file with the restricted secret.
VITE_SMTP_PROJECT_SECRET=your-production-secret-here
Testing Without Adding Domain
Navigate to the public domain of your newly hosted project on Vercel or Netlify (e.g., https://[your-project-name].vercel.app/
).
Now, attempt to send an email. You will see what happens when a request is made from a domain that has not been authorised.
The Result: The request was blocked, and the error message confirms this is because the domain has not been added to the list of authorised origins.
Testing With Domain Added
Now, update your Authorised Origin list in the SMTP Express dashboard. Add your Vercel or Netlify domain (e.g., https://[your-project-name].vercel.app/
).
After saving your changes, return to your hosted project and attempt to send the email again.
The Result: The email will be sent and will not be blocked, as we have already added our domain (hosted on vercel) to the list of authorised origins.
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 repository and follow the detailed setup instructions to see it in action. Explore additional usage instructions in the accompanying GitHub repository: 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 (4)
mails are going to in spam how do I prevent it?
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.
Hi, do you know if it's still working? I tried it and it's great, easy to integrate, and fast, but I used my 2 test emails per day and wanted to upgrade to a premium account but it never takes me to checkout, I tried the support links but messages are never sent.
Any idea why?
Hey! Thanks for the kind words—glad it was helpful! 🙌
The package has had some recent API updates, which might be causing the issue. I'm looking into it and will either update this post or write a follow-up soon. Appreciate your patience!