SmtpClient.php 1.9 KB
<?php

/**
 * 连接代理地址
 * @author:dc
 * @time 2025/3/31 11:27
 * Class ImapClientSwoole
 */
class SmtpClient{

    protected $host = '';

    /**
     * 连接
     * @var \Swoole\Coroutine\Client
     */
    protected $client;

    public function __construct(string $host)
    {
        $this->host = $host;
    }

    /**
     * 打开连接
     * @param string $out_ip
     * @param int $timeout
     * @return string
     * @author:dc
     * @time 2025/3/31 10:27
     */
    public function open(string $out_ip, int $timeout=3){
        $client = new \Swoole\Coroutine\Client(SWOOLE_SOCK_TCP | SWOOLE_SSL);
        $client->set([
//            'timeout'=> $timeout,
            'ssl_verify_peer' => false,// 关闭证书验证
//            'bind_address' => $out_ip,
//            'bind_port' => 36002,
        ]);

        $host = parse_url($this->host);

        if(!$client->connect($host['host'],$host['port'],$timeout)){
            throw new Exception($this->host." connection fail. ".$client->errMsg);
        }

        $this->client = $client;

    }

    /**
     * 写
     * @param string $cmd
     * @return false|int
     * @author:dc
     * @time 2024/9/13 15:47
     */
    public function write(string $cmd){
        if($cmd === "DATA\r\n"){
            $this->is_read = 1;
        }
        if($cmd === ".\r\n"){
            $this->is_read = 0;
        }
        return $this->client->send($cmd);

    }

    protected $is_read = 0;

    /**
     * 读
     * @return false|string
     * @author:dc
     * @time 2024/9/13 15:49
     */
    public function readLine(){
        if($this->is_read === 2){
            return false;
        }

        if($this->is_read === 1){
            $this->is_read = 2;
        }
        return $this->client->recv();

    }


    public function __destruct()
    {
        if(!empty($this->client)) $this->client->close();
        unset($this->client);
        // TODO: Implement __destruct() method.
    }



}