Skip to content

Commit

Permalink
Close connections on unrecoverable errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Rogov Viktor committed Mar 2, 2015
1 parent 6893cfe commit 5dcf395
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
22 changes: 19 additions & 3 deletions src/Smtp.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ public function connect()
if (empty($this->_smtp)) {
if ($this->_smtp = fsockopen($this->_server['host'], $this->_server['port'], $errno, $errstr, $this->_server['timeout'])) {
if (substr($response = fgets($this->_smtp), 0, 3) != self::READY) {
$this->close();
throw new ConnectionException('Server NOT ready! The server responded with this message:' . PHP_EOL . $response);
}

Expand All @@ -131,6 +132,7 @@ public function connect()
$this->_dialog($this->_pass, self::AUTHOK);
}
} else {
$this->_smtp = null;
$message = 'Unable to connect to ' . $this->_server['host'] . ' on port ' . $this->_server['port'] . ' within ' . $this->_server['timeout'] . ' seconds' . PHP_EOL;
if (!empty($errstr)) {
$message .= 'The remote server responded:' . PHP_EOL . $errstr . '(' . $errno . ')';
Expand Down Expand Up @@ -159,7 +161,12 @@ protected function _readResponse($expected, $prevException = null)

if (substr($response, 0, 3) != $expected) {
$type = gettype($response);
$eof = feof($this->_smtp) ? 'EOF - true' : 'EOF - false';
if (feof($this->_smtp)) {
$this->close();
$eof = 'EOF - true';
} else {
$eof = 'EOF - false';
}
$msg = "Unexpected response {$type}:'{$response}'. {$eof}. Expected {$expected}. Here is the dialog dump:\n{$this->_log}";
throw new Exception($msg, 0, $prevException);
}
Expand Down Expand Up @@ -212,15 +219,24 @@ protected function _dialog($request, $expect)
return $this->_readResponse($expect);
}

public function disconnect()
protected function close()
{
if ($this->_smtp) {
$this->_dialog('QUIT', self::BYE);
fclose($this->_smtp);
$this->_smtp = null;
}
}

public function disconnect()
{
if ($this->_smtp) {
try {
$this->_dialog('QUIT', self::BYE);
} catch (Exception $ex) {}
$this->close();
}
}

/**
* Closes connection
*/
Expand Down
1 change: 0 additions & 1 deletion test/SmtpTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ public function testErroneousSmtp()
$smtp->send('[email protected]', 'qwe', 'Test');
} catch (Exception $ex) {
// then verify send is successful after exception
$smtp->generateException = false;
$res = $smtp->send('[email protected]', '[email protected]', 'Test');
$this->assertStringStartsWith('250 ', $res);

Expand Down

0 comments on commit 5dcf395

Please sign in to comment.