0

I am trying to forward contact details from a HTML form to an email address using JS and PHP but I am not receiving any emails in my inbox. I am unsure whether I need to be hosting my website on a server first before the functionality of this will work. The code is below:

HTML:

<section class="contact">

    <div class="content">
    
      <div class="container">
  
        
        <div class="row justify-content-center">
          <div class="col-md-10">
            
            <div class="row align-items-center">
              <div class="col-lg-7 mb-5 mb-lg-0">
  
                <h2 class="mb-5" style="padding-left: 12px;">Say hello.</h2>
  
                <form class="border-right pr-5 mb-5" method="post" id="contactForm" name="contactForm">
                  <div class="row">
                    <div class="col-md-6 form-group">
                      <input type="text" class="form-control" name="fname" id="fname" placeholder="Full Name">
                    </div>
                    <div class="col-md-6 form-group">
                      <input type="text" class="form-control" name="lname" id="phone" placeholder="Phone">
                    </div>
                  </div>
                  <div class="row">
                    <div class="col-md-12 form-group">
                      <input type="text" class="form-control" name="email" id="email" placeholder="Email">
                    </div>
                  </div>
  
                  <div class="row">
                    <div class="col-md-12 form-group">
                      <textarea class="form-control" name="message" id="message" cols="30" rows="7" placeholder="Write your message"></textarea>
                    </div>
                  </div>
                  <div class="row">
                    <div class="col-md-12">
                      <input type="submit" value="Submit" class="btn btn-light rounded-0 py-2 px-4">
                      <span class="submitting"></span>
                    </div>
                  </div>
                </form>
  
                <div id="form-message-warning mt-4"></div> 
                <div id="form-message-success">
                  Your message was sent, thank you!
                </div>
  
              </div>
              <div class="hero__images fade-in-slower">
                <div class="">
                  <img class="middle-img hide-for-mobile" src="images/04.jpeg" alt="" style="width: 330px; margin-top: 65px;">
                </div>
            </div>
            </div>
          </div>  
          </div>
        </div>
    </div>
    
  </section>
  <script src="app/js/script.js"></script>
  <script src="js/jquery-3.3.1.min.js"></script>
  <script src="js/popper.min.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <script src="js/jquery.validate.min.js"></script>
  <script src="js/main.js"></script>

JS

$(function() {

    'use strict';

    // Form

    var contactForm = function() {

        if ($('#contactForm').length > 0 ) {
            $( "#contactForm" ).validate( {
                rules: {
                    fname: "required",
                    lname: "required",
                    email: {
                        required: true,
                        email: true
                    },
                    message: {
                        required: true,
                        minlength: 5
                    }
                },
                messages: {
                    fname: "Please enter your first name",
                    lname: "Please enter your last name",
                    email: "Please enter a valid email address",
                    message: "Please enter a message"
                },
                /* submit via ajax */
                submitHandler: function(form) {     
                    var $submit = $('.submitting'),
                        waitText = 'Submitting...';

                    $.ajax({    
                      type: "POST",
                      url: "php/send-email.php",
                      data: $(form).serialize(),

                      beforeSend: function() { 
                        $submit.css('display', 'block').text(waitText);
                      },
                      success: function(msg) {
                       if (msg == 'OK') {
                        $('#form-message-warning').hide();
                            setTimeout(function(){
                            $('#contactForm').fadeOut();
                        }, 1000);
                            setTimeout(function(){
                               $('#form-message-success').fadeIn();   
                        }, 1400);
                           
                        } else {
                           $('#form-message-warning').html(msg);
                            $('#form-message-warning').fadeIn();
                            $submit.css('display', 'none');
                        }
                      },
                      error: function() {
                        $('#form-message-warning').html("Something went wrong. Please try again.");
                         $('#form-message-warning').fadeIn();
                         $submit.css('display', 'none');
                      }
                  });           
                }
                
            } );
        }
    };
    contactForm();

});

PHP

<?php

$to = 'test@test.com';

function url(){
  return sprintf(
    "%s://%s",
    isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
    $_SERVER['SERVER_NAME']
  );
}

if($_POST) {

   $fname = trim(stripslashes($_POST['fname']));
   $phone = trim(stripslashes($_POST['fname']));
   $email = trim(stripslashes($_POST['email']));
   $subject = trim(stripslashes($_POST['subject']));
   $contact_message = trim(stripslashes($_POST['message']));

   $name = $fname;
   
    if ($subject == '') { $subject = "Contact Form Submission"; }

   // Set Message
   $message .= "Email from: " . $name . "<br />";
   $message .= "Contact number: " . $phone . "<br />";
    $message .= "Email address: " . $email . "<br />";
   $message .= "Message: <br />";
   $message .= nl2br($contact_message);
   $message .= "<br /> ----- <br /> This email was sent from your site " . url() . " contact form. <br />";

   // Set From: header
   $from =  $name . " <" . $email . ">";

   // Email Headers
    $headers = "From: " . $from . "\r\n";
    $headers .= "Reply-To: ". $email . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

   ini_set("sendmail_from", $to); // for windows server
   $mail = mail($to, $subject, $message, $headers);

    if ($mail) { echo "OK"; }
   else { echo "Something went wrong. Please try again."; }

}

?>

Do I need to be hosting my website on a server first for this functionality to work?

beeslaw
  • 21
  • 5
  • Have you tried sending a test email using hard coded values in PHP? You need a mailserver set up for the `mail` function to work correctly, so if you are running this on your local machine, it will not work. – Jacob Mulquin Oct 18 '21 at 08:18
  • @mulquin yes I used a real email address in the PHP code but received no emails – beeslaw Oct 18 '21 at 08:19
  • That's not what I meant by hard coded values, I meant setting `$to`, `$subject` and `$message` manually before the `mail` function (not getting them through the form). – Jacob Mulquin Oct 18 '21 at 08:20
  • @mulquin how would I set up a mailserver for the mail function? – beeslaw Oct 18 '21 at 08:21
  • To be honest, I'd hazard a guess that you are a beginner at this so I would recommend against self-hosting email, instead purchasing a hosting plan with email attached to it. – Jacob Mulquin Oct 18 '21 at 08:22
  • Or for testing you could use PHPMailer and then connect to an existing SMTP such as gmail – ADyson Oct 18 '21 at 08:27

0 Answers0