0

Please not I have made sure that I check every possible questions of this type asked before to find any answer and looks like I'm hitting a snag. I'm not a new developer. But I don't have php experience. I can do just basic stuff. Would really appreciate if some more experienced with PHP and PHPMailer can help.

I have 3 sites. They heavily use the contact form. I have been sharing the same php code for all of them and its been working until i found out yesterday that the mailer is actually not sending the mails.

When i checked into the error logs. This is what i found.

[05-Feb-2019 15:41:03 Africa/Johannesburg] PHP Fatal error:  Uncaught phpmailerException: Could not instantiate mail function. in /home/lovecharmking/public_html/phpmailer/class.phpmailer.php:1509
Stack trace:
#0 /home/lovecharmking/public_html/phpmailer/class.phpmailer.php(1346): PHPMailer->mailSend('Date: Tue, 5 Fe...', '<span><b>Name: ...')
#1 /home/lovecharmking/public_html/phpmailer/class.phpmailer.php(1215): PHPMailer->postSend()
#2 /home/lovecharmking/public_html/contact-form.php(47): PHPMailer->send()
#3 {main} thrown in/home/lovecharmking/public_html/phpmailer/class.phpmailer.php on line 1509.

Here is my code.

<?php
ini_set('display_errors', '1');
require 'PHPMailerAutoload.php';

$contactEmail = $_POST['Email'];
$email2Spa = $_POST['Email2'];
$contactName = $_POST['Name'];
$contactNumber = $_POST['Cell'];
$reason = $_POST['Subject'];
$contactLocation = $_POST['Location'];
$contactMessage = $_POST['Message'];

if(!empty($email2Spa)) die();

$mail = new PHPMailer(true);

$mail->isSMTP();                             // Set mailer to use SMTP
$mail->SMTPDebug = 2;
$mail->SMTPKeepAlive = true;
$mail->Mailer = “smtp”; // don't change the quotes!
$mail->Host = 'mail.domainname.com';             // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                     //  Enable SMTP authentication
$mail->Username = 'help@domainname.com';          // SMTP username
$mail->Password = '**********'; // SMTP password 'TJ&ShBW[H*N#'
$mail->SMTPSecure = 'TLS';                  // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                          // TCP port to connect to

$mail->setFrom('help@domainname.com', $contactName);
$mail->addAddress('help@domainname.com', 'Site Owner');     // Add a recipient
$mail->addReplyTo($contactEmail);
$mail->isHTML(true);  // Set email format to HTML

    $email_body = "";
    $email_body .= "<span><b>Name: </b> " . $contactName . "</span><br/><br/>";
    $email_body .= "<span><b>Reason: </b> " . $reason . "</span><br/><br/>";
    $email_body .= "<span><b>Email Address: </b>" . $contactEmail . "</span><br/>";
    $email_body .= "<p>Phone Number: " . $contactNumber . "</p>";
    $email_body .= "<p><b>Location: </b>" . $contactLocation . "</p>";
    $email_body .= "<p><b>Message: </b>" . $contactMessage . "</p>";

    // $mail->Priority = 1;
    $mail->AddCustomHeader("X-MSMail-Priority: High");
    $mail->AddCustomHeader("Importance: High");
    $mail->Subject = $reason;
    $mail->Body    = $email_body;

if(!$mail->send()) {
    // echo 'Mailer Error: ' . $mail->ErrorInfo;
    // $response = array('success'=>"successfully send", 'message'=>"Message sent.");;
   echo json_encode(array('success' => false, "Mailer Error: ".$mail->ErrorInfo));
} else {
  // return $data['success'] = true;
  // echo json_encode($data);
  // echo 'Message has been sent.';
  echo json_encode(array('success' => true, 'message' => "You message has been sent"));

}.

Here is the Ajax call:

$('#cform').submit(function(e){
  e.preventDefault();
  const formUrl = 'contact-form.php';
  let formData = $('#cform').serialize(); // Collect data from form
  $.ajax({
    type: "POST",
    url: formUrl,
    data: formData,
    timeout: 6000,
    error: function (request, error) {
      console.log(error);},
    success: function (data) {
      var response = JSON.parse(data);
      // console.log(response);
      if (response.success==true) {
        let alertDiv = document.createElement('div');
        alertDiv.innerHTML = `
        <strong>Your Message has been Sent!</strong> Admin will get back to you as soon as he is available.
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
        </button>`
        $('.alert').alert();
        alertDiv.setAttribute('class','alert alert-warning alert-dismissible fade show alertBox');
        alertDiv.setAttribute('role','alert');
        // alertDiv.setAttribute('style','display:inline-block');
        let messageSpan = document.querySelector('.alertMessage');
        let parentForSpan = messageSpan.parentNode;
        parentForSpan.replaceChild(alertDiv,messageSpan);
        // contactForm.appendChild(alertDiv);
        $('#cform')[0].reset();
        // alertDiv.remove()
        // let span = document.createElement('span');
        // span.className = "alertMessage"
        // console.log(response);
      } else {
        console.log('Something wrong is going on. Check it.');
      }
      return false
    }});
    return false;
  });

Here is what the ajax request returns in the browser:

Uncaught SyntaxError: Unexpected token C in JSON at position 1
    at JSON.parse (<anonymous>)
    at Object.success (main.js:212)
    at c (jquery.min.js:4)
    at Object.fireWith [as resolveWith] (jquery.min.js:4)
    at k (jquery.min.js:6)
    at XMLHttpRequest.r (jquery.min.js:6)

Like i said i share the code among the 3 sites at the moment they all not working. They all been running for than years. Any input will be appreciated.

  • Possible duplicate of [phpmailer error "Could not instantiate mail function"](https://stackoverflow.com/questions/1297084/phpmailer-error-could-not-instantiate-mail-function) – matiit Feb 05 '19 at 14:25
  • I saw that question – Bob Masajjage Feb 05 '19 at 14:37
  • But any of those answers didn't help. So I really think it's a different problem. If you can help help. Otherwise dont just mark as possible duplicate. I can't be here to waste peoples time. – Bob Masajjage Feb 05 '19 at 14:39
  • That's why it's called *possible* duplicate. I acknowledge that it didn't help. – matiit Feb 05 '19 at 14:40
  • Does that affect my question ranking. ? Do you think it's a pop version problem. Been looking to sort this out since yesterday already. Problem is all 3 sites are now not working. Should I switch back to the neonal php function? – Bob Masajjage Feb 05 '19 at 14:43
  • I don't know about how it affects question's ranking to be honest. My guess regarding your issue is some missing php extension. Easiest to check will be by trying to use mail() function yourself and see if it works. – matiit Feb 05 '19 at 14:46
  • But it's been working since the sites were uploaded. The thing is I want other people that can help to see the question. – Bob Masajjage Feb 05 '19 at 14:48

1 Answers1

0

This is all caused by this advice:

$mail->Mailer = “smtp”; // don't change the quotes!

That's simply wrong. Those curly quotes are likely to result in Mailer being set to some undefined value, meaning it will fall back to using mail() for sending. You don't need to do this anyway, because your earlier call to isSMTP() sets Mailer correctly (assuming you do actually want to use SMTP), so deleting that line is likely to help.

Nearly every answer on here related to PHPMailer contains a link to the troubleshooting guide, which tells you how to deal with this error: either switch to SMTP, or install a mail server. It also tells you to use the latest version (which you're not), and to base your code on the examples provided (not the incorrect, obsolete, misleading one you're using - I'd like to know where you got it so I can ask them to take it down).

If you're new to PHP (but not coding), the first thing you should do is learn how to use composer; composer to PHP is as gems to ruby, npm to node, pip to python; use it to manage your dependencies, such as PHPMailer.

When dealing with ajax handlers, check that your back-end is producing intelligible results (e.g. valid JSON) before you try to use it from JS, because it's very common to have server-side errors sent to the client (what's happening to you), which will usually not be parseable from JS, and then you have two problems instead of one.

Synchro
  • 35,538
  • 15
  • 81
  • 104
  • Thank you so much @Synchro. I will do the changes and if successful report back. I got the code if I remember from the PHPMailer github page.. I really appreciate your input. – Bob Masajjage Feb 05 '19 at 16:22
  • Thank you so much. Mailer now successfully sending mails has its been. Just getting a json syntax error back now. What does this line really do? echo json_encode(array('success' => true, 'message' => "You message has been sent")); – Bob Masajjage Feb 05 '19 at 16:41
  • **Thank you so much**. Mailer now successfully sending mails has its been. getting a `SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 5 of the JSON data` back now. What does this line really do?=> echo `json_encode(array('success' => true, 'message' => "You message has been sent"));` I went to return an object back to from the server, With a success and message properties. Also can you explain why it worked before? – Bob Masajjage Feb 05 '19 at 16:47
  • Json_encode turns the PHP array into a JSON string representation. It’s likely your output contains some extra white space that breaks JSON validity. Look very closely at the exact response your browser receives. – Synchro Feb 05 '19 at 21:09
  • BTW, your code is clearly based on one of the official examples, but it’s old and contains errors that would never have been in the main github project - like that comment about the quotes - so I suspect it came from somewhere else. – Synchro Feb 05 '19 at 21:11