How to setup email and send it with React

A customer needed a way to send email from their website. Since I didn't have any module for that yet I created a new form module.

Since there is no way to send email directly from React or Javascript, I started to search for a free service that provided a gateway for sending emails.

EmailJS

I found out that EmailJS had just such a service, and it's free, at least the first 200 emails per month. That should be enuff for the client. Create an account, and start by selecting your email provider. Mine is Gmail so that was my choise. It is also important to create a template, because you are going to need the template id.

In my application it's easy to add new modules.

 var Service = {
        pages: [],
        search: {
            path: "/search",
            zone: "BeforeContent",
            includeProps: true
        },
        content: [],
        projects: {
            posts: []
        },
        timeline: {
            id: "1",
            sortorder: 3,
            path: "/",
            zone: "Content",
            style: "",
            title: "Bootproject timeline",
            content: "Latest projects and assignments",
            list: []
        },
        form: {
            zone: "BeforeContent",
            path: "/contact",
        }
    };

The form

import React from 'react';
import * as emailjs from 'emailjs-com'

export default class extends React.Component {
    constructor(props) {
        super(props);
        this.state = { feedback: '', name: 'Bootproject website', email: '', label: '' };
        this.handleChange = this.handleChange.bind(this);
        this.handleChangeEmail = this.handleChangeEmail.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.validateEmail = this.validateEmail.bind(this);
    }

    render() {
        return (
            <section>
                <div className="sharedSection" className="mobile">
                    <div className="sectioncontent">
                        <form className="test-mailing">
                            <p className="accept">{this.state.label}</p>
                            <h2>Send a message to Bootproject</h2>
                            <div>
                                <input type="email"
                                    name="email"
                                    placeholder="Your email"
                                    className="form-control"
                                    required
                                    value={this.state.email}
                                    onChange={this.handleChangeEmail} />
                            </div><br />
                            <div>
                                <textarea
                                    id="test-mailing"
                                    name="test-mailing"
                                    onChange={this.handleChange}
                                    placeholder="Write your message here."
                                    required
                                    value={this.state.feedback}
                                    style={{ width: '100%', height: '150px' }}
                                    className="form-control"
                                />
                            </div><br/>
                            <input type="button" value="Submit" className="btn btn--submit" onClick={this.handleSubmit} />
                            </form>
                    </div>
                </div>
            </section>

        )
    }

    handleChange(event) {
        this.setState({ feedback: event.target.value })
    }

    handleChangeEmail(event) {
        this.setState({ email: event.target.value })
    }

    handleSubmit(event) {

        if (!this.state.email) {
            alert("Enter a valid email address!")
            return;
        }
        if (!this.state.feedback) {
            alert("Hummm... No need to send an email without any content. Try again please.");
            return;
        }

        if (this.validateEmail(this.state.email)) {
            const templateId = 'template_YOURID';
            this.sendFeedback(templateId, { message_html: this.state.feedback, from_name: this.state.name, reply_to: this.state.email });
        }
    }

    sendFeedback(templateId, variables) {
        emailjs.init("user_YOURID");

        emailjs.send(
            'gmail', templateId,
            variables
        ).then(res => {
            console.log('Email successfully sent!');

            this.setState({
                label: 'Thank you!!',
            });

            setTimeout(
                function () {
                    this.setState({
                        label: '',
                        feedback: '',
                        email: ''
                    });
                }.bind(this),
                3000);

        })
        .catch(err => console.error('Oh well, you failed. Here some thoughts on the error that occured:', err))
    }

    validateEmail(mail) {
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail)) {
            return (true)
        }
        alert("You have entered an invalid email address!")
        return (false)
    }
}

The installation id will you find in Installation page in the dashboard.
This seamless installation was up and running in minits! I like it when it's fast and free, dont you!!

Read more on their website


Created by Bootproject editor on 2020-02-07


  • multi

    About

    The Swede(me), Rickard Magnusson a Senior Software Engineer, currently employeed as a freelance consultant in Norway.

  • Legal

    Bootproject.se and Footer.se is property of Bootproject and may be used under (MIT)licence . See project on Bitbucket

  • Logo Contact

    Email: bootproject@icloud.com

(©) Copyright www.bootproject.no 2020