PHPMailer\PHPMailer

SMTP::connect()publicWP 1.0

Connect to an SMTP server.

Method of the class: SMTP{}

No Hooks.

Return

true|false.

Usage

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

SMTP::connect() code WP 6.4.3

public function connect($host, $port = null, $timeout = 30, $options = [])
{
    //Clear errors to avoid confusion
    $this->setError('');
    //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
    $this->edebug(
        "Connection: opening to $host:$port, timeout=$timeout, options=" .
        (count($options) > 0 ? var_export($options, true) : 'array()'),
        self::DEBUG_CONNECTION
    );

    $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
    //https://tools.ietf.org/html/rfc5321#section-3.1
    if ($responseCode === 554) {
        $this->quit();
    }
    //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);
    $this->close();
    return false;
}