Search code examples
phpgmailphpmailer

phpmailer, code worked with different email, but switching to gmail with app password: "Mailer Error: Could not instantiate mail function."


I had a working site contact form with PHPmailer going through hosting email. Changed to Gmail, and now the form no longer sends email, instead returns "Mailer Error: Could not instantiate mail function.". I've pulled an app password from gmail and am using it. Does anyone see any problems that would prevent sending emails with Gmail here? Are the app passwords not working any further?

<?php

    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;

    $myEmail = "********@gmail.com";
    $myEmailPassword = "**** **** **** ****";
    $myPersonalEmail = "**********";

    require './src/Exception.php';
    require './src/PHPMailer.php';
    require './src/SMTP.php';


        $mail = new PHPMailer(true);

try {

        $mail->SMTPDebug = 0;

        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = $myEmail;
        $mail->Password = $myEmailPassword;
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;

        $mail->setFrom($myEmail, 'Mailer');
        $mail->addAddress($myPersonalEmail);
    $mail->addReplyTo($_POST['email'], $_POST['name']);

        $mail->isHTML(true);   
    $mail->Subject = $_POST['subject']; 
        $mail->Body = $_POST['message'];


$response = $_POST["g-recaptcha-response"];

    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $data = array(
        'secret' => '********************',
        'response' => $_POST["g-recaptcha-response"]
    );
    $options = array(
        'http' => array (
            'method' => 'POST',
            'content' => http_build_query($data)
        )
    );
    $context  = stream_context_create($options);
    $verify = file_get_contents($url, false, $context);
    $captcha_success=json_decode($verify);

    if ($captcha_success->success==false) {
        echo "<p>Please try the captcha again.</p>";
        echo "<br><a href=\"javascript:history.go(-1)\">Go Back To Form</a>";        
    } else if ($captcha_success->success==true) {
        
        $mail->send();
    echo 'Your message was sent successfully!';
    }
        } catch (Exception $e) { // handle error.
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
?>

This worked to send emails until I changed the email, password, and host inputs. After I changed them, I get "Message could not be sent. Mailer Error: Could not instantiate mail function."


Solution

  • You've made a simple mistake here; You have not called isSMTP(), so none of your SMTP settings are being used, and its trying to send through a local mail server using the PHP mail() function instead, but you don't have a local mail server configured, which results in this error message.

    Add this line to your code:

    $mail->isSMTP();