PHPMailer虚拟主机发信错误两种解决办法connect to SMTP host

 PHPMailer是一个非常棒的开源邮件类,使用也非常简单,但是对于虚拟主机来说,往往要受到各种限制。刚才我在虚拟主机上使用PHPMailer就遇到一个“SMTP Error: Could not connect to SMTP host”错误。

如下错误:

Fatal error: Uncaught exception 'phpmailerException' with message 'SMTP Error: Data not accepted.' in /webHome/host4512576/www/phpmailer/class.phpmailer.php:757 Stack trace: #0 /webHome/host4512576/www/phpmailer/class.phpmailer.php(576): PHPMailer->SmtpSend('Date: Tue, 22 M...', '?????????xiaoda...') #1 /webHome/host4512576/www/mail.php(23): PHPMailer->Send() #2 {main} thrown in /webHome/host4512576/www/phpmailer/class.phpmailer.php on line 757

 

下面介绍两种解决办法:

这个错误说明虚拟主机不支持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:

 

在 class.phpmailer.php 中,将

function IsSMTP() {

       $this->Mailer = 'smtp';

}

改成:

function IsSMTP() {

          $this->Mailer = 'SMTP';

}

再次测试,终于看到了熟悉的面孔,  QQ右下角提示 收到新邮件!问题解决!舒心呀!

后来我发现并不是因为修改了smtp为SMTP之后却能够发送邮件,这个并不是因为有些邮件服务器不能接受smtp的原因,而是并不是使用了smtp来发送邮件,PHPmailer里有一个判断的函数,
public function IsSMTP() {
      $this->Mailer = 'SMTP';
}

switch($this->Mailer) {
     case 'sendmail':
            return $this->SendmailSend($header, $body);
     case 'smtp'://由于SMTP和smtp不相等 所以选择的是下面MailSend发送邮件 并不是使用smtp发送邮件
            return $this->SmtpSend($header, $body);
     default:
            return $this->MailSend($header, $body);

}

方法2:

 

将fsockopen函数替换成pfsockopen函数

因为pfsockopen的参数与fsockopen基本一致,所以只需要将@fsockopen替换成@pfsockopen就可以了。

 

方法3:

使用stream_socket_client函数

一般fsockopen()被禁,pfsockopen也有可能被禁,所以这里介绍另一个函数stream_socket_client()。

stream_socket_client的参数与fsockopen有所不同,所以代码要修改为:

$this->smtp_conn = stream_socket_client("tcp://".$host.":".$port, $errno,  $errstr,  $tval);

这样就可以了。

stream_socket_client($host.":80", $errno, $errstr, 30);