Search code examples
phpwordpressphpmailer

PHPMailer Call to a member function isSMTP() on null


I'm trying to update my Wordpress plugin since the location of PHPMailer is moved in wordpress 5.5.

I'm testing in Wordpress version 5.1 right now and i'm encountering the following error

Fatal error: Call to a member function isSMTP() on null in (path) on line (line)

As shown in the code below i've tried var_dumping the class methods and it shows isSMTP but when i call it a line later it returns the error.

      if (!class_exists("\\PHPMailer")) {
        global $wp_version;
        if ( version_compare( $wp_version, '5.5', '<' ) ) {
          require_once(\ABSPATH . \WPINC . "/class-phpmailer.php");
          require_once(\ABSPATH . \WPINC . "/class-smtp.php");
          require_once(\ABSPATH . \WPINC . "/class-pop3.php");
          $oPhpMailer = new \PHPMailer();
        }else {
          require_once(\ABSPATH . \WPINC . "/PHPMailer/PHPMailer.php");
          require_once(\ABSPATH . \WPINC . "/PHPMailer/SMTP.php");
          require_once(\ABSPATH . \WPINC . "/class-pop3.php");
          $oPhpMailer = new PHPMailer();
        }
      }

      var_dump(get_class_methods($oPhpMailer));
      $oPhpMailer->isSMTP();

Solution

  • Looks like if (!class_exists("\\PHPMailer")) returns false (which means the class exists). You don't set $oPhpMailer in this case which means $oPhpMailer = null. That is what the error means: you cannot run null->isSMTP().

    It could very well be that this code is ran twice - the first time the $oPhpMailer gets set because the class does not exists (which is why you get the get_class_methods output). The second time the class exists, so the variable is null.

    Try adding an else

    if (!class_exists("\\PHPMailer")) {
      // ...
    } else {
      $oPhpMailer = new \PHPMailer();
    }