Email For React & Php

Project Structure

  • Main Folder
    • mail Folder
      • classesFolder
        • sendmail.php
      • config.php
      • email.php
    • app
      • public
      • src
        • app.js
//email.php

<?php
include_once('classes/sendmail.php');
include_once('config.php');

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: Content-Type');
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);

if( empty($_POST['firstName']) && empty($_POST['email']) ) {
    echo json_encode(
        [
           "sent" => false,
           "message" => $SendMailEmptyerrorMessage
        ]
    ); 
    exit();
}

if ($_POST){
    //@important: Please change this before using
    http_response_code(200);
    $subject = 'Contact from: ' . $_POST['firstName'];
    $from = $_POST['email'];
    $message = $_POST['msg'];       
    //Actual sending email
    $sendEmail = new Sender( $from,$adminEmail, $subject, $message);
    $sendEmail->send();
} else {
 // tell the user about error
 echo json_encode(
     [
        "sent" => false,
        "message" => $SendMailFailederrorMessage
     ]
 );
}
?>
//Config.php

<?php
$adminEmail =  "hello@malith.dev"; //Please change this to yours
$SendMailFailederrorMessage = "Something went wrong";
$SendMailEmptyerrorMessage = "Empty form";
?>

//Sendmaill.php

<?php
/**
 * @class Sender
 * This is used to send email via react contact from component
 */
class Sender
{
    public $sendTo;
    public $sendFrom;
    public $subject;
    public $message;
    public $headers;
    public $error = [];

    public function __construct($sendTo, $sendFrom = null, $subject, $message)
    {
        $this->sendTo = $sendTo;
        $this->sendFrom = ($sendFrom) ? $sendFrom : 'hey@malith.dev';
        $this->subject = $subject;
        $this->message = $message;
    }

    public function setTo($email, $name) {
        return $this->sendTo = $email;
    }

    public function getTo() {
        return $this->sendTo;
    }

    public function setFrom($email, $name)  {
        return $this->sendFrom = $email;
    }

    public function setSubject($subject) {
        return $this->subject = $subject;
    }

    public function getSubject() {
        return $this->subject;
    }

    public function setMessage($message) {
        $this->message = $message;
        return $this;
    }

    public function getMessage() {
        return $this->message;
    }

    public function setHeader() {
        $headers = 'From: '.$this->getFrom() . "\r\n" .
            'Reply-To: '.$this->getFrom() . "\r\n" .
            'X-Mailer: PHP/' . phpversion();

        $this->headers = $headers;
        return $this;
    }

    public function getFrom() {
        return $this->sendFrom;
    }

    public function send() {
        $to = $this->sendTo;
        $from = $this->sendFrom;
        $subject = $this->subject;
        $message = $this->message;
        //$headers = $this->headers;
        $headers = 'From: '.$this->getFrom() . "\r\n" .
            'Reply-To: '.$this->getFrom() . "\r\n" .
            'X-Mailer: PHP/' . phpversion();

        mail($to, $subject, $message, $headers);
        echo json_encode(array("sent" => true));
    }
}

?>

React Project...

import logo from './logo.svg';
import './App.css';
import axios from "axios"
import {useState} from "react"


function App() {

  const[firstName,setFirstname] = useState("")
  const[email,setEmail] = useState("")
  const[msg,setMsg] = useState("")
 

  const handleChange = (e) => {
		setFirstname(e.target.value);
   
	};
  const handleChange1 = (e) => {
		setEmail(e.target.value);
	};
  const handleChange2 = (e) => {
		setMsg(e.target.value);
	};
 

  const handleSubmit = e => {
    e.preventDefault();
    const data = {
      firstName: firstName,
      email: email,
 
      msg:msg
    };
    axios({
      method: "post",
      url: `http://localhost/mail/email.php`,
      headers: { "content-type": "application/json" },
      data: data
    })
      .then(res => console.log(res))
      .catch(err => console.log(err));
      console.log(data)
  };



  return (

    <div>
     <input value={firstName}  onChange={handleChange} />
      <input type="email" value={email} onChange={handleChange1}/>
      {/* <input value={number} onChange={handleChange3}/> */}
      <input type="textarea" value={msg} onChange={handleChange2}/>
      <button onClick={handleSubmit}>Login</button>
     
    </div>
   
  );
}

export default App;

Set the Project Structure and you are good to go.

Did you find this article useful?