用socket_create和socket_connect替换fsockopen

时间:2012-01-11 16:01:12

标签: php email sockets phpmailer

我正在使用phpmailer发送电子邮件,并且当我需要连接到远程邮件服务器时,在我的主机上发送时遇到了一些问题。 我从技术支持获得了我需要将我的服务器ip与远程服务器绑定的信息。 这是我第一次搞乱套接字。

不幸的是phpmailer使用fsocketopen,所以这就是我改变它的方式:

//my replacement code
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$conn = socket_connect($socket, $host, $port);
if($conn) {
    $this->smtp_conn = $socket;
} else {
    throw new Exception("Failed to connect to server: ".socket_last_error($socket));
}

//original phpmailer code
/**
$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
 */

但在改变之后我收到了警告:

  • 警告:fputs():提供的资源不是有效的流资源

  • 警告:socket_get_status():提供的资源不是有效的流 资源

如何创建与fsockopen返回的资源兼容的资源? 使用var_dump表示这两个vars都是套接字。但是我仍然收到资源创建的使用socket_create的警告。

2 个答案:

答案 0 :(得分:0)

您需要返回流资源,而不是套接字资源。尝试使用函数stream_socket_client()。

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

此外,您确定您的托管服务提供商允许您直接从服务器发送电子邮件吗?有时他们会提供一个中继邮件服务器供您用于出站电子邮件。

答案 1 :(得分:0)

请参阅this answer

你也可以问我自己为PHPMailer实现的smtp-class插件,它可以在一台计算机上发送来自diffenet IP的电子邮件。请参阅我的帐户中的联系人。

P.S。对不起我的英文