From 0f84aff7472d66b5ec21068c17b75625b7bc4f65 Mon Sep 17 00:00:00 2001 From: Jared Hancock <jared@osticket.com> Date: Thu, 23 Jan 2014 12:28:19 -0600 Subject: [PATCH] smtp: Reuse existing connections where possible This should speed up the system where several emails and alerts will be sent through the same SMTP account in the same request. --- include/class.mailer.php | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/include/class.mailer.php b/include/class.mailer.php index 21a7d157d..51db63cee 100644 --- a/include/class.mailer.php +++ b/include/class.mailer.php @@ -198,21 +198,38 @@ class Mailer { $body = $mime->get($encodings); //encode the headers. $headers = $mime->headers($headers, true); + + // Cache smtp connections made during this request + static $smtp_connections = array(); if(($smtp=$this->getSMTPInfo())) { //Send via SMTP - $mail = mail::factory('smtp', - array ('host' => $smtp['host'], - 'port' => $smtp['port'], - 'auth' => $smtp['auth'], - 'username' => $smtp['username'], - 'password' => $smtp['password'], - 'timeout' => 20, - 'debug' => false, - )); + $key = sprintf("%s:%s:%s", $smtp['host'], $smtp['port'], + $smtp['username']); + if (!isset($smtp_connections[$key])) { + $mail = mail::factory('smtp', array( + 'host' => $smtp['host'], + 'port' => $smtp['port'], + 'auth' => $smtp['auth'], + 'username' => $smtp['username'], + 'password' => $smtp['password'], + 'timeout' => 20, + 'debug' => false, + 'persist' => true, + )); + if ($mail->connect()) + $smtp_connections[$key] = $mail; + } + else { + // Use persistent connection + $mail = $smtp_connections[$key]; + } $result = $mail->send($to, $headers, $body); if(!PEAR::isError($result)) return $messageId; + // Force reconnect on next ->send() + unset($smtp_connections[$key]); + $alert=sprintf("Unable to email via SMTP:%s:%d [%s]\n\n%s\n", $smtp['host'], $smtp['port'], $smtp['username'], $result->getMessage()); $this->logError($alert); -- GitLab