In this post I'm going to cover some methods on how to do it simply.
First of all, you cannot send emails with just React, you have to use 3rd party tools to do it. EmailJS lets you set up sending without touching the backend at all. You just have to connect the email client and create templates. As for email clients, you can use whichever you like: Gmail, Outlook or more pricey ones like Mailgun.
Let's proceed with the most common one - Gmail.
First step - sign up at https://www.emailjs.com. Then, build your email template. There is a ready template builder for it. You can add attachments, auto-reply or dynamic variables.
Image credit: Mailtraps tutorial on sending emails using ReactJS
Next step is connecting EmailJS to the React project. You can do it with npm.
Now, let us send the email itself. You can send simple emails with emailjs.send and forms with emailjs.send.Form.
As for forms, you should put the following code into the src/Form.js file of your project:
Expand|Select|Wrap|Line Numbers
- import React from 'react';
- export default class extends React.Component {
- constructor(props) {
- super(props);
- this.state = { feedback: '', name: 'Name', email: 'email@example.com' };
- this.handleChange = this.handleChange.bind(this);
- this.handleSubmit = this.handleSubmit.bind(this);
- }
- render() {
- return (
- <form className="test-mailing">
- <h1>Let's see if it works</h1>
- <div>
- <textarea
- id="test-mailing"
- name="test-mailing"
- onChange={this.handleChange}
- placeholder="Post some lorem ipsum here"
- required
- value={this.state.feedback}
- style={{width: '100%', height: '150px'}}
- />
- </div>
- <input type="button" value="Submit" className="btn btn--submit" onClick={this.handleSubmit} />
- </form>
- )
- }
- handleChange(event) {
- this.setState({feedback: event.target.value})
- }
- handleSubmit() {
- }
- }
Expand|Select|Wrap|Line Numbers
- handleSubmit (event) {
- const templateId = 'template_id';
- this.sendFeedback(templateId, {message_html: this.state.feedback, from_name: this.state.name, reply_to: this.state.email})
- }
- sendFeedback (templateId, variables) {
- window.emailjs.send(
- 'gmail', templateId,
- variables
- ).then(res => {
- console.log('Email successfully sent!')
- })
- // Handle errors here however you like, or use a React error boundary
- .catch(err => console.error('Oh well, you failed. Here some thoughts on the error that occured:', err))
- }
And you are ready to go! See, simple?