3 * PHPMailer RFC821 SMTP email transport class.
6 * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
8 * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
9 * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
10 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
11 * @author Brent R. Matzelle (original founder)
12 * @copyright 2012 - 2017 Marcus Bointon
13 * @copyright 2010 - 2012 Jim Jagielski
14 * @copyright 2004 - 2009 Andy Prevost
15 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
16 * @note This program is distributed in the hope that it will be useful - WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18 * FITNESS FOR A PARTICULAR PURPOSE.
21 namespace PHPMailer\PHPMailer
;
24 * PHPMailer RFC821 SMTP email transport class.
25 * Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server.
28 * @author Marcus Bointon <phpmailer@synchromedia.co.uk>
33 * The PHPMailer SMTP version number.
37 const VERSION
= '6.0.5';
40 * SMTP line break constant.
47 * The SMTP port to use if one is not specified.
51 const DEFAULT_PORT
= 25;
54 * The maximum line length allowed by RFC 2822 section 2.1.1.
58 const MAX_LINE_LENGTH
= 998;
61 * Debug level for no output.
66 * Debug level to show client -> server messages.
68 const DEBUG_CLIENT
= 1;
71 * Debug level to show client -> server and server -> client messages.
73 const DEBUG_SERVER
= 2;
76 * Debug level to show connection status, client -> server and server -> client messages.
78 const DEBUG_CONNECTION
= 3;
81 * Debug level to show all messages.
83 const DEBUG_LOWLEVEL
= 4;
88 * * self::DEBUG_OFF (`0`) No debug output, default
89 * * self::DEBUG_CLIENT (`1`) Client commands
90 * * self::DEBUG_SERVER (`2`) Client commands and server responses
91 * * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status
92 * * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages.
96 public $do_debug = self
::DEBUG_OFF
;
99 * How to handle debug output.
101 * * `echo` Output plain-text as-is, appropriate for CLI
102 * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
103 * * `error_log` Output to error log as configured in php.ini
104 * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
107 * $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
110 * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug`
111 * level output is used:
114 * $mail->Debugoutput = new myPsr3Logger;
117 * @var string|callable|\Psr\Log\LoggerInterface
119 public $Debugoutput = 'echo';
122 * Whether to use VERP.
124 * @see http://en.wikipedia.org/wiki/Variable_envelope_return_path
125 * @see http://www.postfix.org/VERP_README.html Info on VERP
129 public $do_verp = false;
132 * The timeout value for connection, in seconds.
133 * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
134 * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure.
136 * @see http://tools.ietf.org/html/rfc2821#section-4.5.3.2
140 public $Timeout = 300;
143 * How long to wait for commands to complete, in seconds.
144 * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
148 public $Timelimit = 300;
151 * Patterns to extract an SMTP transaction id from reply to a DATA command.
152 * The first capture group in each regex will be used as the ID.
153 * MS ESMTP returns the message ID, which may not be correct for internal tracking.
157 protected $smtp_transaction_id_patterns = [
158 'exim' => '/[0-9]{3} OK id=(.*)/',
159 'sendmail' => '/[0-9]{3} 2.0.0 (.*) Message/',
160 'postfix' => '/[0-9]{3} 2.0.0 Ok: queued as (.*)/',
161 'Microsoft_ESMTP' => '/[0-9]{3} 2.[0-9].0 (.*)@(?:.*) Queued mail for delivery/',
162 'Amazon_SES' => '/[0-9]{3} Ok (.*)/',
163 'SendGrid' => '/[0-9]{3} Ok: queued as (.*)/',
167 * The last transaction ID issued in response to a DATA command,
168 * if one was detected.
170 * @var string|bool|null
172 protected $last_smtp_transaction_id;
175 * The socket for the server connection.
179 protected $smtp_conn;
182 * Error information, if any, for the last SMTP command.
190 'smtp_code_ex' => '',
194 * The reply the server sent to us for HELO.
195 * If null, no HELO string has yet been received.
199 protected $helo_rply = null;
202 * The set of SMTP extensions sent in reply to EHLO command.
203 * Indexes of the array are extension names.
204 * Value at index 'HELO' or 'EHLO' (according to command that was sent)
205 * represents the server name. In case of HELO it is the only element of the array.
206 * Other values can be boolean TRUE or an array containing extension options.
207 * If null, no HELO/EHLO string has yet been received.
211 protected $server_caps = null;
214 * The most recent reply received from the server.
218 protected $last_reply = '';
221 * Output debugging info via a user-selected method.
223 * @param string $str Debug string to output
224 * @param int $level The debug level of this message; see DEBUG_* constants
226 * @see SMTP::$Debugoutput
227 * @see SMTP::$do_debug
229 protected function edebug($str, $level = 0)
231 if ($level > $this->do_debug
) {
234 //Is this a PSR-3 logger?
235 if ($this->Debugoutput
instanceof \Psr\Log\LoggerInterface
) {
236 $this->Debugoutput
->debug($str);
240 //Avoid clash with built-in function names
241 if (!in_array($this->Debugoutput
, ['error_log', 'html', 'echo']) and is_callable($this->Debugoutput
)) {
242 call_user_func($this->Debugoutput
, $str, $level);
246 switch ($this->Debugoutput
) {
248 //Don't output, just log
252 //Cleans up output a bit for a better looking, HTML-safe output
253 echo gmdate('Y-m-d H:i:s'), ' ', htmlentities(
254 preg_replace('/[\r\n]+/', '', $str),
261 //Normalize line breaks
262 $str = preg_replace('/\r\n|\r/ms', "\n", $str);
263 echo gmdate('Y-m-d H:i:s'),
265 //Trim trailing space
267 //Indent for readability, except for trailing break
279 * Connect to an SMTP server.
281 * @param string $host SMTP server IP or host name
282 * @param int $port The port number to connect to
283 * @param int $timeout How long to wait for the connection to open
284 * @param array $options An array of options for stream_context_create()
288 public function connect($host, $port = null, $timeout = 30, $options = [])
291 //This is enabled by default since 5.0.0 but some providers disable it
292 //Check this once and cache the result
293 if (null === $streamok) {
294 $streamok = function_exists('stream_socket_client');
296 // Clear errors to avoid confusion
298 // Make sure we are __not__ connected
299 if ($this->connected()) {
300 // Already connected, generate error
301 $this->setError('Already connected to a server');
306 $port = self
::DEFAULT_PORT
;
308 // Connect to the SMTP server
310 "Connection: opening to $host:$port, timeout=$timeout, options=" .
311 (count($options) > 0 ?
var_export($options, true) : 'array()'),
312 self
::DEBUG_CONNECTION
317 $socket_context = stream_context_create($options);
318 set_error_handler([$this, 'errorHandler']);
319 $this->smtp_conn
= stream_socket_client(
324 STREAM_CLIENT_CONNECT
,
327 restore_error_handler();
329 //Fall back to fsockopen which should work in more places, but is missing some features
331 'Connection: stream_socket_client not available, falling back to fsockopen',
332 self
::DEBUG_CONNECTION
334 set_error_handler([$this, 'errorHandler']);
335 $this->smtp_conn
= fsockopen(
342 restore_error_handler();
344 // Verify we connected properly
345 if (!is_resource($this->smtp_conn
)) {
347 'Failed to connect to server',
353 'SMTP ERROR: ' . $this->error
['error']
354 . ": $errstr ($errno)",
360 $this->edebug('Connection: opened', self
::DEBUG_CONNECTION
);
361 // SMTP server can take longer to respond, give longer timeout for first read
362 // Windows does not have support for this timeout function
363 if (substr(PHP_OS
, 0, 3) != 'WIN') {
364 $max = ini_get('max_execution_time');
365 // Don't bother if unlimited
366 if (0 != $max and $timeout > $max) {
367 @set_time_limit
($timeout);
369 stream_set_timeout($this->smtp_conn
, $timeout, 0);
371 // Get any announcement
372 $announce = $this->get_lines();
373 $this->edebug('SERVER -> CLIENT: ' . $announce, self
::DEBUG_SERVER
);
379 * Initiate a TLS (encrypted) session.
383 public function startTLS()
385 if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
389 //Allow the best TLS version(s) we can
390 $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT
;
392 //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT
393 //so add them back in manually if we can
394 if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
395 $crypto_method |
= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
;
396 $crypto_method |
= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
;
399 // Begin encrypted connection
400 set_error_handler([$this, 'errorHandler']);
401 $crypto_ok = stream_socket_enable_crypto(
406 restore_error_handler();
408 return (bool) $crypto_ok;
412 * Perform SMTP authentication.
413 * Must be run after hello().
417 * @param string $username The user name
418 * @param string $password The password
419 * @param string $authtype The auth type (CRAM-MD5, PLAIN, LOGIN, XOAUTH2)
420 * @param OAuth $OAuth An optional OAuth instance for XOAUTH2 authentication
422 * @return bool True if successfully authenticated
424 public function authenticate(
430 if (!$this->server_caps
) {
431 $this->setError('Authentication is not allowed before HELO/EHLO');
436 if (array_key_exists('EHLO', $this->server_caps
)) {
437 // SMTP extensions are available; try to find a proper authentication method
438 if (!array_key_exists('AUTH', $this->server_caps
)) {
439 $this->setError('Authentication is not allowed at this stage');
440 // 'at this stage' means that auth may be allowed after the stage changes
441 // e.g. after STARTTLS
446 $this->edebug('Auth method requested: ' . ($authtype ?
$authtype : 'UNSPECIFIED'), self
::DEBUG_LOWLEVEL
);
448 'Auth methods available on the server: ' . implode(',', $this->server_caps
['AUTH']),
452 //If we have requested a specific auth type, check the server supports it before trying others
453 if (null !== $authtype and !in_array($authtype, $this->server_caps
['AUTH'])) {
454 $this->edebug('Requested auth method not available: ' . $authtype, self
::DEBUG_LOWLEVEL
);
458 if (empty($authtype)) {
459 //If no auth mechanism is specified, attempt to use these, in this order
460 //Try CRAM-MD5 first as it's more secure than the others
461 foreach (['CRAM-MD5', 'LOGIN', 'PLAIN', 'XOAUTH2'] as $method) {
462 if (in_array($method, $this->server_caps
['AUTH'])) {
467 if (empty($authtype)) {
468 $this->setError('No supported authentication methods found');
472 self
::edebug('Auth method selected: ' . $authtype, self
::DEBUG_LOWLEVEL
);
475 if (!in_array($authtype, $this->server_caps
['AUTH'])) {
476 $this->setError("The requested authentication method \"$authtype\" is not supported by the server");
480 } elseif (empty($authtype)) {
485 // Start authentication
486 if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
489 // Send encoded username and password
490 if (!$this->sendCommand(
492 base64_encode("\0" . $username . "\0" . $password),
500 // Start authentication
501 if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
504 if (!$this->sendCommand('Username', base64_encode($username), 334)) {
507 if (!$this->sendCommand('Password', base64_encode($password), 235)) {
512 // Start authentication
513 if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
517 $challenge = base64_decode(substr($this->last_reply
, 4));
519 // Build the response
520 $response = $username . ' ' . $this->hmac($challenge, $password);
522 // send encoded credentials
523 return $this->sendCommand('Username', base64_encode($response), 235);
525 //The OAuth instance must be set up prior to requesting auth.
526 if (null === $OAuth) {
529 $oauth = $OAuth->getOauth64();
531 // Start authentication
532 if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
537 $this->setError("Authentication method \"$authtype\" is not supported");
546 * Calculate an MD5 HMAC hash.
547 * Works like hash_hmac('md5', $data, $key)
548 * in case that function is not available.
550 * @param string $data The data to hash
551 * @param string $key The key to hash with
555 protected function hmac($data, $key)
557 if (function_exists('hash_hmac')) {
558 return hash_hmac('md5', $data, $key);
561 // The following borrowed from
562 // http://php.net/manual/en/function.mhash.php#27225
564 // RFC 2104 HMAC implementation for php.
565 // Creates an md5 HMAC.
566 // Eliminates the need to install mhash to compute a HMAC
569 $bytelen = 64; // byte length for md5
570 if (strlen($key) > $bytelen) {
571 $key = pack('H*', md5($key));
573 $key = str_pad($key, $bytelen, chr(0x00));
574 $ipad = str_pad('', $bytelen, chr(0x36));
575 $opad = str_pad('', $bytelen, chr(0x5c));
576 $k_ipad = $key ^
$ipad;
577 $k_opad = $key ^
$opad;
579 return md5($k_opad . pack('H*', md5($k_ipad . $data)));
583 * Check connection state.
585 * @return bool True if connected
587 public function connected()
589 if (is_resource($this->smtp_conn
)) {
590 $sock_status = stream_get_meta_data($this->smtp_conn
);
591 if ($sock_status['eof']) {
592 // The socket is valid but we are not connected
594 'SMTP NOTICE: EOF caught while checking if connected',
602 return true; // everything looks good
609 * Close the socket and clean up the state of the class.
610 * Don't use this function without first trying to use QUIT.
614 public function close()
617 $this->server_caps
= null;
618 $this->helo_rply
= null;
619 if (is_resource($this->smtp_conn
)) {
620 // close the connection and cleanup
621 fclose($this->smtp_conn
);
622 $this->smtp_conn
= null; //Makes for cleaner serialization
623 $this->edebug('Connection: closed', self
::DEBUG_CONNECTION
);
628 * Send an SMTP DATA command.
629 * Issues a data command and sends the msg_data to the server,
630 * finializing the mail transaction. $msg_data is the message
631 * that is to be send with the headers. Each header needs to be
632 * on a single line followed by a <CRLF> with the message headers
633 * and the message body being separated by an additional <CRLF>.
634 * Implements RFC 821: DATA <CRLF>.
636 * @param string $msg_data Message data to send
640 public function data($msg_data)
642 //This will use the standard timelimit
643 if (!$this->sendCommand('DATA', 'DATA', 354)) {
647 /* The server is ready to accept data!
648 * According to rfc821 we should not send more than 1000 characters on a single line (including the LE)
649 * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
650 * smaller lines to fit within the limit.
651 * We will also look for lines that start with a '.' and prepend an additional '.'.
652 * NOTE: this does not count towards line-length limit.
655 // Normalize line breaks before exploding
656 $lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $msg_data));
658 /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
659 * of the first line (':' separated) does not contain a space then it _should_ be a header and we will
660 * process all lines before a blank line as headers.
663 $field = substr($lines[0], 0, strpos($lines[0], ':'));
665 if (!empty($field) and strpos($field, ' ') === false) {
669 foreach ($lines as $line) {
671 if ($in_headers and $line == '') {
674 //Break this line up into several smaller lines if it's too long
675 //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len),
676 while (isset($line[self
::MAX_LINE_LENGTH
])) {
677 //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on
678 //so as to avoid breaking in the middle of a word
679 $pos = strrpos(substr($line, 0, self
::MAX_LINE_LENGTH
), ' ');
680 //Deliberately matches both false and 0
682 //No nice break found, add a hard break
683 $pos = self
::MAX_LINE_LENGTH
- 1;
684 $lines_out[] = substr($line, 0, $pos);
685 $line = substr($line, $pos);
687 //Break at the found point
688 $lines_out[] = substr($line, 0, $pos);
689 //Move along by the amount we dealt with
690 $line = substr($line, $pos +
1);
692 //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1
694 $line = "\t" . $line;
697 $lines_out[] = $line;
699 //Send the lines to the server
700 foreach ($lines_out as $line_out) {
701 //RFC2821 section 4.5.2
702 if (!empty($line_out) and $line_out[0] == '.') {
703 $line_out = '.' . $line_out;
705 $this->client_send($line_out . static::LE
, 'DATA');
709 //Message data has been sent, complete the command
710 //Increase timelimit for end of DATA command
711 $savetimelimit = $this->Timelimit
;
712 $this->Timelimit
= $this->Timelimit
* 2;
713 $result = $this->sendCommand('DATA END', '.', 250);
714 $this->recordLastTransactionID();
716 $this->Timelimit
= $savetimelimit;
722 * Send an SMTP HELO or EHLO command.
723 * Used to identify the sending server to the receiving server.
724 * This makes sure that client and server are in a known state.
725 * Implements RFC 821: HELO <SP> <domain> <CRLF>
728 * @param string $host The host name or IP to connect to
732 public function hello($host = '')
734 //Try extended hello first (RFC 2821)
735 return (bool) ($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host));
739 * Send an SMTP HELO or EHLO command.
740 * Low-level implementation used by hello().
742 * @param string $hello The HELO string
743 * @param string $host The hostname to say we are
749 protected function sendHello($hello, $host)
751 $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
752 $this->helo_rply
= $this->last_reply
;
754 $this->parseHelloFields($hello);
756 $this->server_caps
= null;
763 * Parse a reply to HELO/EHLO command to discover server extensions.
764 * In case of HELO, the only parameter that can be discovered is a server name.
766 * @param string $type `HELO` or `EHLO`
768 protected function parseHelloFields($type)
770 $this->server_caps
= [];
771 $lines = explode("\n", $this->helo_rply
);
773 foreach ($lines as $n => $s) {
774 //First 4 chars contain response code followed by - or space
775 $s = trim(substr($s, 4));
779 $fields = explode(' ', $s);
780 if (!empty($fields)) {
783 $fields = $fields[0];
785 $name = array_shift($fields);
788 $fields = ($fields ?
$fields[0] : 0);
791 if (!is_array($fields)) {
799 $this->server_caps
[$name] = $fields;
805 * Send an SMTP MAIL command.
806 * Starts a mail transaction from the email address specified in
807 * $from. Returns true if successful or false otherwise. If True
808 * the mail transaction is started and then one or more recipient
809 * commands may be called followed by a data command.
810 * Implements RFC 821: MAIL <SP> FROM:<reverse-path> <CRLF>.
812 * @param string $from Source address of this message
816 public function mail($from)
818 $useVerp = ($this->do_verp ?
' XVERP' : '');
820 return $this->sendCommand(
822 'MAIL FROM:<' . $from . '>' . $useVerp,
828 * Send an SMTP QUIT command.
829 * Closes the socket if there is no error or the $close_on_error argument is true.
830 * Implements from RFC 821: QUIT <CRLF>.
832 * @param bool $close_on_error Should the connection close if an error occurs?
836 public function quit($close_on_error = true)
838 $noerror = $this->sendCommand('QUIT', 'QUIT', 221);
839 $err = $this->error
; //Save any error
840 if ($noerror or $close_on_error) {
842 $this->error
= $err; //Restore any error from the quit command
849 * Send an SMTP RCPT command.
850 * Sets the TO argument to $toaddr.
851 * Returns true if the recipient was accepted false if it was rejected.
852 * Implements from RFC 821: RCPT <SP> TO:<forward-path> <CRLF>.
854 * @param string $address The address the message is being sent to
858 public function recipient($address)
860 return $this->sendCommand(
862 'RCPT TO:<' . $address . '>',
868 * Send an SMTP RSET command.
869 * Abort any transaction that is currently in progress.
870 * Implements RFC 821: RSET <CRLF>.
872 * @return bool True on success
874 public function reset()
876 return $this->sendCommand('RSET', 'RSET', 250);
880 * Send a command to an SMTP server and check its return code.
882 * @param string $command The command name - not sent to the server
883 * @param string $commandstring The actual command to send
884 * @param int|array $expect One or more expected integer success codes
886 * @return bool True on success
888 protected function sendCommand($command, $commandstring, $expect)
890 if (!$this->connected()) {
891 $this->setError("Called $command without being connected");
895 //Reject line breaks in all commands
896 if (strpos($commandstring, "\n") !== false or strpos($commandstring, "\r") !== false) {
897 $this->setError("Command '$command' contained line breaks");
901 $this->client_send($commandstring . static::LE
, $command);
903 $this->last_reply
= $this->get_lines();
904 // Fetch SMTP code and possible error code explanation
906 if (preg_match('/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/', $this->last_reply
, $matches)) {
908 $code_ex = (count($matches) > 2 ?
$matches[2] : null);
909 // Cut off error code from each response line
910 $detail = preg_replace(
912 ($code_ex ?
str_replace('.', '\\.', $code_ex) . ' ' : '') . '/m',
917 // Fall back to simple parsing if regex fails
918 $code = substr($this->last_reply
, 0, 3);
920 $detail = substr($this->last_reply
, 4);
923 $this->edebug('SERVER -> CLIENT: ' . $this->last_reply
, self
::DEBUG_SERVER
);
925 if (!in_array($code, (array) $expect)) {
927 "$command command failed",
933 'SMTP ERROR: ' . $this->error
['error'] . ': ' . $this->last_reply
,
946 * Send an SMTP SAML command.
947 * Starts a mail transaction from the email address specified in $from.
948 * Returns true if successful or false otherwise. If True
949 * the mail transaction is started and then one or more recipient
950 * commands may be called followed by a data command. This command
951 * will send the message to the users terminal if they are logged
952 * in and send them an email.
953 * Implements RFC 821: SAML <SP> FROM:<reverse-path> <CRLF>.
955 * @param string $from The address the message is from
959 public function sendAndMail($from)
961 return $this->sendCommand('SAML', "SAML FROM:$from", 250);
965 * Send an SMTP VRFY command.
967 * @param string $name The name to verify
971 public function verify($name)
973 return $this->sendCommand('VRFY', "VRFY $name", [250, 251]);
977 * Send an SMTP NOOP command.
978 * Used to keep keep-alives alive, doesn't actually do anything.
982 public function noop()
984 return $this->sendCommand('NOOP', 'NOOP', 250);
988 * Send an SMTP TURN command.
989 * This is an optional command for SMTP that this class does not support.
990 * This method is here to make the RFC821 Definition complete for this class
991 * and _may_ be implemented in future.
992 * Implements from RFC 821: TURN <CRLF>.
996 public function turn()
998 $this->setError('The SMTP TURN command is not implemented');
999 $this->edebug('SMTP NOTICE: ' . $this->error
['error'], self
::DEBUG_CLIENT
);
1005 * Send raw data to the server.
1007 * @param string $data The data to send
1008 * @param string $command Optionally, the command this is part of, used only for controlling debug output
1010 * @return int|bool The number of bytes sent to the server or false on error
1012 public function client_send($data, $command = '')
1014 //If SMTP transcripts are left enabled, or debug output is posted online
1015 //it can leak credentials, so hide credentials in all but lowest level
1016 if (self
::DEBUG_LOWLEVEL
> $this->do_debug
and
1017 in_array($command, ['User & Password', 'Username', 'Password'], true)) {
1018 $this->edebug('CLIENT -> SERVER: <credentials hidden>', self
::DEBUG_CLIENT
);
1020 $this->edebug('CLIENT -> SERVER: ' . $data, self
::DEBUG_CLIENT
);
1022 set_error_handler([$this, 'errorHandler']);
1023 $result = fwrite($this->smtp_conn
, $data);
1024 restore_error_handler();
1030 * Get the latest error.
1034 public function getError()
1036 return $this->error
;
1040 * Get SMTP extensions available on the server.
1042 * @return array|null
1044 public function getServerExtList()
1046 return $this->server_caps
;
1050 * Get metadata about the SMTP server from its HELO/EHLO response.
1051 * The method works in three ways, dependent on argument value and current state:
1052 * 1. HELO/EHLO has not been sent - returns null and populates $this->error.
1053 * 2. HELO has been sent -
1054 * $name == 'HELO': returns server name
1055 * $name == 'EHLO': returns boolean false
1056 * $name == any other string: returns null and populates $this->error
1057 * 3. EHLO has been sent -
1058 * $name == 'HELO'|'EHLO': returns the server name
1059 * $name == any other string: if extension $name exists, returns True
1060 * or its options (e.g. AUTH mechanisms supported). Otherwise returns False.
1062 * @param string $name Name of SMTP extension or 'HELO'|'EHLO'
1066 public function getServerExt($name)
1068 if (!$this->server_caps
) {
1069 $this->setError('No HELO/EHLO was sent');
1074 if (!array_key_exists($name, $this->server_caps
)) {
1075 if ('HELO' == $name) {
1076 return $this->server_caps
['EHLO'];
1078 if ('EHLO' == $name ||
array_key_exists('EHLO', $this->server_caps
)) {
1081 $this->setError('HELO handshake was used; No information about server extensions available');
1086 return $this->server_caps
[$name];
1090 * Get the last reply from the server.
1094 public function getLastReply()
1096 return $this->last_reply
;
1100 * Read the SMTP server's response.
1101 * Either before eof or socket timeout occurs on the operation.
1102 * With SMTP we can tell if we have more lines to read if the
1103 * 4th character is '-' symbol. If it is a space then we don't
1104 * need to read anything else.
1108 protected function get_lines()
1110 // If the connection is bad, give up straight away
1111 if (!is_resource($this->smtp_conn
)) {
1116 stream_set_timeout($this->smtp_conn
, $this->Timeout
);
1117 if ($this->Timelimit
> 0) {
1118 $endtime = time() +
$this->Timelimit
;
1120 $selR = [$this->smtp_conn
];
1122 while (is_resource($this->smtp_conn
) and !feof($this->smtp_conn
)) {
1123 //Must pass vars in here as params are by reference
1124 if (!stream_select($selR, $selW, $selW, $this->Timelimit
)) {
1126 'SMTP -> get_lines(): timed-out (' . $this->Timeout
. ' sec)',
1127 self
::DEBUG_LOWLEVEL
1131 //Deliberate noise suppression - errors are handled afterwards
1132 $str = @fgets
($this->smtp_conn
, 515);
1133 $this->edebug('SMTP INBOUND: "' . trim($str) . '"', self
::DEBUG_LOWLEVEL
);
1135 // If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled),
1136 // or 4th character is a space, we are done reading, break the loop,
1137 // string array access is a micro-optimisation over strlen
1138 if (!isset($str[3]) or (isset($str[3]) and $str[3] == ' ')) {
1141 // Timed-out? Log and break
1142 $info = stream_get_meta_data($this->smtp_conn
);
1143 if ($info['timed_out']) {
1145 'SMTP -> get_lines(): timed-out (' . $this->Timeout
. ' sec)',
1146 self
::DEBUG_LOWLEVEL
1150 // Now check if reads took too long
1151 if ($endtime and time() > $endtime) {
1153 'SMTP -> get_lines(): timelimit reached (' .
1154 $this->Timelimit
. ' sec)',
1155 self
::DEBUG_LOWLEVEL
1165 * Enable or disable VERP address generation.
1167 * @param bool $enabled
1169 public function setVerp($enabled = false)
1171 $this->do_verp
= $enabled;
1175 * Get VERP address generation mode.
1179 public function getVerp()
1181 return $this->do_verp
;
1185 * Set error messages and codes.
1187 * @param string $message The error message
1188 * @param string $detail Further detail on the error
1189 * @param string $smtp_code An associated SMTP error code
1190 * @param string $smtp_code_ex Extended SMTP code
1192 protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '')
1195 'error' => $message,
1196 'detail' => $detail,
1197 'smtp_code' => $smtp_code,
1198 'smtp_code_ex' => $smtp_code_ex,
1203 * Set debug output method.
1205 * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it
1207 public function setDebugOutput($method = 'echo')
1209 $this->Debugoutput
= $method;
1213 * Get debug output method.
1217 public function getDebugOutput()
1219 return $this->Debugoutput
;
1223 * Set debug output level.
1227 public function setDebugLevel($level = 0)
1229 $this->do_debug
= $level;
1233 * Get debug output level.
1237 public function getDebugLevel()
1239 return $this->do_debug
;
1245 * @param int $timeout The timeout duration in seconds
1247 public function setTimeout($timeout = 0)
1249 $this->Timeout
= $timeout;
1257 public function getTimeout()
1259 return $this->Timeout
;
1263 * Reports an error number and string.
1265 * @param int $errno The error number returned by PHP
1266 * @param string $errmsg The error message returned by PHP
1267 * @param string $errfile The file the error occurred in
1268 * @param int $errline The line number the error occurred on
1270 protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0)
1272 $notice = 'Connection failed.';
1279 "$notice Error #$errno: $errmsg [$errfile line $errline]",
1280 self
::DEBUG_CONNECTION
1285 * Extract and return the ID of the last SMTP transaction based on
1286 * a list of patterns provided in SMTP::$smtp_transaction_id_patterns.
1287 * Relies on the host providing the ID in response to a DATA command.
1288 * If no reply has been received yet, it will return null.
1289 * If no pattern was matched, it will return false.
1291 * @return bool|null|string
1293 protected function recordLastTransactionID()
1295 $reply = $this->getLastReply();
1297 if (empty($reply)) {
1298 $this->last_smtp_transaction_id
= null;
1300 $this->last_smtp_transaction_id
= false;
1301 foreach ($this->smtp_transaction_id_patterns
as $smtp_transaction_id_pattern) {
1302 if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
1303 $this->last_smtp_transaction_id
= trim($matches[1]);
1309 return $this->last_smtp_transaction_id
;
1313 * Get the queue/transaction ID of the last SMTP transaction
1314 * If no reply has been received yet, it will return null.
1315 * If no pattern was matched, it will return false.
1317 * @return bool|null|string
1319 * @see recordLastTransactionID()
1321 public function getLastTransactionID()
1323 return $this->last_smtp_transaction_id
;