PHPMailer是一個非常棒的開源郵件類,使用也非常簡單,但是對于虛擬主機來說,往往要受到各種限制。剛才我在虛擬主機上使用PHPMailer就遇到一個“SMTP Error: Could not connect to SMTP host”錯誤。下面介紹兩種解決辦法:
這個錯誤說明虛擬主機不支持PHPMailer默認調用的fsockopen函數,找到class.smtp.php文件,搜索fsockopen,就找到了這樣一段代碼:
// connect to the smtp server
$this->smtp_conn = @fsockopen($host,// the host of the server
$port,// the port to use
$errno, // error number if any
$errstr, // error message if any
$tval); // give up after ? secs
方法1:將fsockopen函數替換成pfsockopen函數
因為pfsockopen的參數與fsockopen基本一致,所以只需要將@fsockopen替換成@pfsockopen就可以了。
方法2:使用stream_socket_client函數
一般fsockopen()被禁,pfsockopen也有可能被禁,所以這里介紹另一個函數stream_socket_client()。
stream_socket_client的參數與fsockopen有所不同,所以代碼要修改為:
$this->smtp_conn = stream_socket_client("tcp://".$host.":".$port, $errno, $errstr, $tval);
這樣就可以了。