0

My PHP contact form isn't working. When I try to submit a message, I am only given the error message "Error sending email!".

I'm just learning PHP, does the PHP file that contains my HTML need to have an opening "<?php" & a closing "?>" anywhere?

Appreciate any help, tips & advice.

contactForm.php

<?php if(isset($_POST['cf_submit'])) {    
   $errors = array();
   $success = null;
   
   $required_fields['cf_name'] = 'You are required to enter your name.';
   $required_fields['cf_email'] = 'You are required to enter your e-mail Address.';
   $required_fields['cf_subject'] = 'You are required to enter a subject.';
   $required_fields['cf_message'] = 'You are required to enter a message.';
                   
   foreach($_POST as $key => $value) {
      if(array_key_exists($key, $required_fields)) {
         if(trim($_POST[$key]) === '') {
             $errors[$key] = $required_fields[$key];
          }
       }
    }

    if(empty($errors)) {
         $to = "MY EMAIL ADDRESS";
         $subject = $_POST['cf_subject'];
         $name_field = $_POST['cf_name'];
         $email_field = $_POST['cf_email'];
         $message = $_POST['cf_message'];
        
         $body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message";
         $success = mail($to, $subject, $body);
    }
    
    if($success) {
              echo "<p><strong>Thank you for getting in touch. Expect to hear back from us soon.</strong></p>";
         } else {
              echo "Error sending email!";
         }
    }

    if(!empty($errors)) {
         echo "<strong>Please check the following errors:</strong><br/><br/>";
         echo "<ul>";
         foreach($errors as $value) {         
              echo "<li>$value</li>";      
         }
         echo "</ul>";
    } ?>

HTML form

<form action="contactForm.php" method="post">
<!-- Name -->
<input name="cf_name" type="text" id="cf_name" class="cf_input" value="<?php if(isset($_POST['cf_name'])) echo $_POST['cf_name'];?>" placeholder="Name">
    
<!-- Email -->
<input name="cf_email" type="email" id="cf_email" class="cf_input" value="<?php if(isset($_POST['cf_email'])) echo $_POST['cf_email'];?>" placeholder="Email">
    
<!-- Subject -->
<input name="cf_subject" type="text" id="cf_subject"  class="cf_input" value="<?php if(isset($_POST['cf_subject'])) echo $_POST['cf_subject'];?>" placeholder="Subject">
    
<!-- Message -->
<textarea name="cf_message" cols="45" rows="3" id="cf_message" value="<?php if(isset($_POST['cf_message'])) echo $_POST['cf_message'];?>" placeholder="Enter message here" class="cf_text"></textarea>
                                        
<!-- Submit -->
<button type="submit" name="cf_submit">Send Message</button>
</form>
brombeer
  • 8,716
  • 5
  • 21
  • 27
  • Are you sure that your server has enabled you to send email thru PHP ? – Ken Lee Dec 13 '20 at 17:34
  • Thanks for the comment! I’m using XAMPP to work on the files, I will look into whether that is suitable or not. – CameronWhyte Dec 13 '20 at 17:51
  • Does this answer your question? [PHP mail function doesn't complete sending of e-mail](https://stackoverflow.com/questions/24644436/php-mail-function-doesnt-complete-sending-of-e-mail) – ADyson Dec 13 '20 at 18:49
  • xamp by default can not send email thats why you are always getting error you have to setup xamp for sending email or use phmailer library and connect any/your gmail account with it and send email – Hammad Ahmed khan Dec 14 '20 at 06:27

1 Answers1

0

Download the php mailer from https://github.com/PHPMailer/PHPMailer and use it.

To use it: first you need to create a folder called "phpmailer". And then put the php mailer folder you downloaded in it.

then use this code:

<?php
    header("Access-Control-Allow-Origin: *");
    header('Access-control-Allow-Headers: Authorization,Content-Type ,X-Auth-Token , Origin');
   $username=$_POST["email"];
   $password=$_POST["password"];
   $to=$_POST["to"];
   $subject=$_POST["subject"];
   $body=$_POST["body"];

   // Import PHPMailer classes into the global namespace
   // These must be at the top of your script, not inside a function
   use PHPMailer\PHPMailer\PHPMailer;
   use PHPMailer\PHPMailer\SMTP;
   use PHPMailer\PHPMailer\Exception;

   // Load Composer's autoloader
   require 'phpmailer/src/PHPMailer.php';
   require 'phpmailer/src/SMTP.php';
   require 'phpmailer/src/Exception.php';

   // Instantiation and passing `true` enables exceptions
   $mail = new PHPMailer(true);

   try {
    //Server settings
     $mail->SMTPDebug = 2;                      // Enable verbose debug output
     $mail->isSMTP();                                            // Send using SMTP
     $mail->Host       = 'smtp.gmail.com';                    // Set the SMTP    server    to send through
     $mail->SMTPAuth   = true;                                   // Enable SMTP      authentication
    $mail->Username   = $username;                     // SMTP username
    $mail->Password   = $password;                               // SMTP password
    $mail->SMTPSecure = 'tls';         // Enable TLS encryption; `  PHPMailer::ENCRYPTION_SMTPS` encouraged
    $mail->Port       = 587;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

//Recipients
   $mail->setFrom('no-reply@gmail.com',$username);
   $mail->addAddress($to);     // Add a recipient


   // Attachments
   // $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
   // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

   // Content
   $mail->isHTML(true);                                  // Set email format to HTML
   $mail->Subject = $subject;
   $mail->Body    = $body;
   //$mail->AltBody =;

   $mail->send();

   echo "<script>";
   echo "window.alert('Email was sent')";
   echo "</script>";


  } catch (Exception $e) {
  echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
  }
 ?>

Also make sure you turn "less secure app access" on for this to work. Because such codes use existing email to send emails. The easiest way is to use your gmail account.

Charbelalam
  • 104
  • 7
  • *”The mail function does not work anymore“*? The [PHP mail function](https://www.php.net/manual/en/function.mail.php) is alive and well. Please consider correcting the incorrect assertion. – Tim Morton Dec 13 '20 at 23:13