SMTP::connect()publicWP 1.0

Connect to an SMTP server.

Method of the class: SMTP{}

No Hooks.




$SMTP = new SMTP();
$SMTP->connect( $host, $port, $timeout, $options );
$host(string) (required)
SMTP server IP or host name
The port number to connect to
Default: null
How long to wait for the connection to open
Default: 30
An array of options for stream_context_create()
Default: []

SMTP::connect() code WP 6.6

public function connect($host, $port = null, $timeout = 30, $options = [])
    //Clear errors to avoid confusion
    //Make sure we are __not__ connected
    if ($this->connected()) {
        //Already connected, generate error
        $this->setError('Already connected to a server');

        return false;
    if (empty($port)) {
        $port = self::DEFAULT_PORT;
    //Connect to the SMTP server
        "Connection: opening to $host:$port, timeout=$timeout, options=" .
        (count($options) > 0 ? var_export($options, true) : 'array()'),

    $this->smtp_conn = $this->getSMTPConnection($host, $port, $timeout, $options);

    if ($this->smtp_conn === false) {
        //Error info already set inside `getSMTPConnection()`
        return false;

    $this->edebug('Connection: opened', self::DEBUG_CONNECTION);

    //Get any announcement
    $this->last_reply = $this->get_lines();
    $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
    $responseCode = (int)substr($this->last_reply, 0, 3);
    if ($responseCode === 220) {
        return true;
    //Anything other than a 220 response means something went wrong
    //RFC 5321 says the server will wait for us to send a QUIT in response to a 554 error
    if ($responseCode === 554) {
    //This will handle 421 responses which may not wait for a QUIT (e.g. if the server is being shut down)
    $this->edebug('Connection: closing due to error', self::DEBUG_CONNECTION);
    return false;