Search code examples
phpemailsmtpphpmailer

PHPmailer is not working on live server using gmail smtp with cakePHP 3


I use cakePHP 3, when I moved my app to server, it stopped sending emails, I am using gmail smtp server. I tried with SSL connect to smtp.gmail.com on port 465, still not working. Also variable $mail->SMTPDebug = on; is making some troubles.

My send function is this:

  public function send($to, $subject, $message) {
    $sender = "[email protected]"; // this will be overwritten by GMail

    $header = "X-Mailer: PHP/".phpversion() . "Return-Path: $sender";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: text/html; charset=UTF-8\r\n";

    $mail = new \PHPMailer();

    $mail->IsSMTP();
    $mail->Host = "aspmx.l.google.com";
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = "ssl";
    $mail->Port = 25;
    $mail->SMTPDebug  = on; // turn it off in production
    $mail->Username   = "........";
    $mail->Password   = "........";

    $mail->From = $sender;
    $mail->FromName = "From Me";

    $mail->AddAddress($to);

    $mail->IsHTML(true);
    $mail->CreateHeader($header);

    $mail->Subject = $subject;
    $mail->Body    = nl2br($message);
    $mail->AltBody = nl2br($message);

    // return an array with two keys: error & message
    if(!$mail->Send()) {
        return array('error' => true, 'message' => 'Mailer Error: ' . $mail->ErrorInfo);
    } else {
        return array('error' => false, 'message' =>  "Message sent!");
    }
}
}

my error is this:

Use of undefined constant on - assumed 'on' [APP/Controller/Component/EmailComponent.php, line 30]

Undefined variable: errno [ROOT/vendor/phpmailer/class.smtp.php, line 182]

Undefined variable: errstr [ROOT/vendor/phpmailer/class.smtp.php, line 183]

Is is possible that webhosting on which I have page is blocking it?

Thank you


Solution

  • There's some misunderstanding of basic PHP syntax happening here. Have you tried reading the manual?

    In this case, on (as well as being just plain invalid PHP) is not a valid value for SMTPDebug, even if you make it a string. Try setting it to 2, as the docs suggest.

    Your code is something of a mess - you're trying to break bits of PHPMailer (don't try to set headers yourself like that, let PHPMailer do it properly); you've based your code on an obsolete example, and are using an old version of PHPMailer; You're talking to the wrong address to send out through gmail - it should be smtp.gmail.com; You're trying to use SSL on a non-SSL port; You're putting HTML tags into the plain text version.

    There's just too much wrong here to be worth fixing, so I suggest you start again with a clean, working example, and update to the latest PHPMailer.

    As far as problems connecting to gmail go, this is also very well covered by the troubleshooting guide and by many other questions on SO.