Razi Melliti
Razi Melliti

Reputation: 210

how to send email with react.js front end?

i have created a websites and deployed it ( using react js ) in my website there is a contact form which will send the client message to my work email ( [email protected]) . i know i can't send email with react js because rereact only handle the front end so i'm looking for a solution using nodemailer or other solutions ! how can i do that ?

i tried the following tutorials to link react with express : [https://medium.com/@maison.moa/setting-up-an-express-backend-server-for-create-react-app-bc7620b20a61][1]

i made a quick app for testing : folder structure :

client ( created with create-react app )
node_modules
config.js
package.json
package_lock.json
server.js

in the front end : client/src app.js code :

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Form from './Form.js';

class App extends Component {
state = {
    data: null
  };

  componentDidMount() {
      // Call our fetch function below once the component mounts
    this.callBackendAPI()
      .then(res => this.setState({ data: res.express }))
      .catch(err => console.log(err));
  }
    // Fetches our GET route from the Express server. (Note the route we are fetching matches the GET route from server.js
  callBackendAPI = async () => {
    const response = await fetch('/express_backend');
    const body = await response.json();

    if (response.status !== 200) {
      throw Error(body.message) 
    }
    return body;
  };

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
      <Form/>
        <p className="App-intro">{this.state.data}</p>
      </div>
    );
  }
}

export default App;

Email.js code :

import React from 'react';
import { Email, Item, A} from 'react-html-email';
export default function InlineLink({name, children}) {
  return (
  <Email title='link'>
    <Item>
       Hello {name}
       <p>helooo</p>
    </Item>
    <Item>
      {children}
    </Item>
  </Email>
)};

Form.js code :

import MyEmail from './Email'
import { renderEmail } from 'react-html-email'
import axios from 'axios';
import React, { Component } from 'react';

class Form extends Component {

    resetForm(){

        this.setState({feedback: ''});
    }

    constructor(props) {
        super(props);
        this.state = { feedback: '', name: 'Name', email: '[email protected]' };
        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(event){

    const messageHtml =  renderEmail(
      <MyEmail name={this.state.name}> {this.state.feedback}</MyEmail>
    );
    
            axios({
                method: "POST", 
                url:"http://localhost:3000/send", 
                data: {
              name: this.state.name,
              email: this.state.email,
              messageHtml: messageHtml
                }
            }).then((response)=>{
                if (response.data.msg === 'success'){
                    alert("Email sent, awesome!"); 
                    this.resetForm()
                }else if(response.data.msg === 'fail'){
                    alert("Oops, something went wrong. Try again")
                }
            })
        }
}
export default Form;

in the backend server.js code :

const express = require('express');
const app = express();
const port = process.env.PORT || 5000;

// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));

// create a GET route
app.get('/express_backend', (req, res) => {
  res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
});
const nodemailer = require('nodemailer');
const creds = require('./config');

var transport = {
  host: 'smtp.gmail.com', // e.g. smtp.gmail.com
  auth: {
    user: creds.USER,
    pass: creds.PASS
  }
}

var transporter = nodemailer.createTransport(transport)

transporter.verify((error, success) => {
  if (error) {
    console.log(error);
  } else {
    console.log('All works fine, congratz!');
  }
});
app.use(express.json()); app.post('/send', (req, res, next) => {
    const name = req.body.name
    const email = req.body.email
    const message = req.body.messageHtml
  
  
    var mail = {
      from: name,
      to: '[email protected]',  
      subject: 'Contact form request',
  
      html: message
    }
  
    transporter.sendMail(mail, (err, data) => {
      if (err) {
        res.json({
          msg: 'fail'
        })
      } else {
        res.json({
          msg: 'success'
        })
      }
    })
  })

config.js code :

module.exports = {
    USER: '[email protected]', 
    PASS: 'my_email_password',
}

even that it shows the error message which is "Oops, something went wrong. Try again" [1]: https://medium.com/@maison.moa/setting-up-an-express-backend-server-for-create-react-app-bc7620b20a61

Upvotes: 1

Views: 22089

Answers (2)

SHREEVARSHAN K
SHREEVARSHAN K

Reputation: 36

Please Refer the Below code , Which is working for me..

Paste the below Code in FrontEnd i.e React (app.js)

    import React,{useState,useEffect} from "react"
import Axios from 'axios'
import './App.css';



function App() {
const [frommail,setfrommail]=useState("")
const [password,setpassword]=useState(0)
const [tomail,settomail]=useState("")

useEffect(()=>{
  Axios.get("http://localhost:3001/read").then((response)=>{
    console.log(response.data)
  })
},[])


const sendmail=()=>{
  Axios.post("http://localhost:3001/mail",{frommail:frommail,password:password,tomail:tomail}).then((response)=>{
    if (response.data.msg === 'success'){
        alert("Email sent, awesome!"); 
   
    }else if(response.data.msg === 'fail'){
        alert("Oops, something went wrong. Try again")
    }
})

}


  return (
    <div className="App">
     
      <label>From</label>
      <input type="text" onChange={(e)=>{setfrommail(e.target.value)}}/>
      <label>From Mail Password</label>
      <input type="text" onChange={(e)=>{setpassword(e.target.value)}}/>
      <label>To address</label>
      <input type="text" onChange={(e)=>{settomail(e.target.value)}}/>
      <input type="submit" onClick={sendmail}/>

    </div>
  );
}

export default App;

Then Here is the code For Backend i.e Node js

const express = require("express");

const app = express();
const cors=require('cors')
var nodemailer = require('nodemailer');



app.use(express.json());
app.use(cors())



app.post(("/mail"),async (req,res)=>{
  const frommail=req.body.frommail
  const password = req.body.password
  const tomail=req.body.tomail
  var transporter = nodemailer.createTransport({
    service: 'gmail',

    auth: {
      user: frommail,
      pass: password
    }
  });
  
  var mailOptions = {
    from: frommail,
    to: tomail,
    subject: 'Sending Email using Node.js',
    text: `sending mail using Node.js was running successfully. Hope it help you. For more code and project Please Refer my github page`
    // html: '<h1>Hi Smartherd</h1><p>Your Messsage</p>'        
  };
  
  transporter.sendMail(mailOptions, function(error, info){
    if (error) {
      res.json({
        msg: 'fail'
      });
    } 
    else{
      res.json({
        msg: 'success'
      })
    }
  });

})

app.listen(3001, () => {
  console.log("Server is Running");
});

Finally Ensure that your From mail id have a less secure app access:

check this feature is enable in your gmail account

Upvotes: 2

Edwin Barahona
Edwin Barahona

Reputation: 189

Nodemailer might do the trick for you, in essence you will need an email account that supports smtp, node v6 or above and Nodemailer Documentation (there's a how to example) it supports ssl, Oauth authentication and DKIM. Depending on what you need specificly there are other options like mailgun and mailchimp that provide APIs or backend with PHP or Java

Upvotes: 1

Related Questions