felix_xiao felix_xiao - 1 year ago 415
Javascript Question

Send an Email Using React.js + Express.js

I have built a web app using React.js in ES6. I currently want to create a basic "Contact Us" page and want to send an email. I am new to React and just discovered that I cannot actually send an email using React itself. I'm following the tutorial with

but have had some difficulty integrating the example code with my React files. Specifically, calling
node expressFile.js
works, but I have no idea how to link this to my React front-end.

Nodemailer: https://github.com/nodemailer/nodemailer

Express-mailer: https://www.npmjs.com/package/express-mailer

My React component for the form is below. How would I write an Express file so that it is called from the
method in my React component? Thanks!

import React from 'react';
import {
} from 'react-bootstrap';

class ContactView extends React.Component{
contactUs() {
// TODO: Send the email here

return (
<Input type="email" ref="contact_email" placeholder="Your email address"/>
<Input type="text" ref="contact_subject" placeholder="Subject"/>
<Input type="textarea" ref="contact_content" placeholder="Content"/>
<Button onClick={this.contactUs.bind(this)} bsStyle="primary" bsSize="large">Submit</Button>

export default ContactView;

Answer Source

When the button is clicked, execute an ajax POST request to your express server, i.e "/contactus". /contactus can fetch the email, subject, and content out of the post data and send to the mail function.

In React:

    url: '/contactus',
    dataType: 'json',
    cache: false,
    success: function(data) {
        // Success..
    error: function(xhr, status, err) {
        console.error(status, err.toString());

In express add the nodemailer code within an express post handler:

app.post('/contactus', function (req, res) {
    // node mailer code