Almost all the web applications we create, we need to send emails to users, whether it be a support email or verification one. In the below article we will go through all the steps of sending emails directly with ReactJs.
All we need is a basic knowledge of React and EmailJs account.
So developers fasten up your seat belt! Here we go !! 🚀
1. Creating EmailJs account
- Click on the link and create a free account on EmailJs
- Select the service you want to start with. I am using Gmail Service.
- Connect your account and click on add service.
- You will see Gmail service in added services .
2. Creating mail template
- In your EmailJs dashboard click on Email Templates -> Create New template. Setup your template name and id.
- You can configure the template as per your requirement.
- You can use curly braces for the fields that will receive data from react code as shown below. I have made "To email" field dynamic.
3. Time for some code .. 😎
- Create a new React App
- Install the EmailJs package using command
$ npm install emailjs-com --save
- Import Email js in your App.js file
import * as emailjs from "emailjs-com";
- Grab the service Id and template id from your template-> Copy Code
- Copy your user id from Account-> API Keys -> User ID
- Modify your App.js file
<div className="App"> | |
<header className="App-header"> | |
<img src={logo} className="App-logo" alt="logo" /> | |
<p> | |
Enter your email here | |
<input type="email" onChange={event => setEmail(event.target.value)}/> | |
<button type="submit" | |
onClick={handleClick} | |
>Send mail</button> | |
</p> | |
</header> | |
</div> |
- Create the handleChange function
function handleClick() { | |
console.log(email) | |
var data = { | |
to_email:email, | |
}; | |
emailjs.send(SERVICE_ID, TEMPLATE_ID, data, USER_ID).then( | |
function (response) { | |
console.log(response.status, response.text); | |
}, | |
function (err) { | |
console.log(err); | |
} | |
); | |
} |
And you are done!!!
Woo! now you can send emails directly from react . 🎉
You can find the complete code on my github repository React-Emailjs
Top comments (2)
very rushed and incomplete.
Hey Mate this is not working anymore
Some comments have been hidden by the post's author - find out more