Debian Codegraph @

vendor/pear/mail/Mail/smtp.php

raw
1 <?php
2 /**
3 * SMTP implementation of the PEAR Mail interface. Requires the Net_SMTP class.
4 *
5 * PHP version 5
6 *
7 * LICENSE:
8 *
9 * Copyright (c) 2010-2021, Chuck Hagenbuch & Jon Parise
10 * All rights reserved.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 *
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 *
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 *
23 * 3. Neither the name of the copyright holder nor the names of its
24 * contributors may be used to endorse or promote products derived from
25 * this software without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 *
39 * @category HTTP
40 * @package HTTP_Request
41 * @author Jon Parise <[email protected]>
42 * @author Chuck Hagenbuch <[email protected]>
43 * @copyright 2010-2021 Chuck Hagenbuch
44 * @license http://opensource.org/licenses/BSD-3-Clause New BSD License
45 * @version CVS: $Id$
46 * @link http://pear.php.net/package/Mail/
47 */
48
49 /** Error: Failed to create a Net_SMTP object */
50 define('PEAR_MAIL_SMTP_ERROR_CREATE', 10000);
51
52 /** Error: Failed to connect to SMTP server */
53 define('PEAR_MAIL_SMTP_ERROR_CONNECT', 10001);
54
55 /** Error: SMTP authentication failure */
56 define('PEAR_MAIL_SMTP_ERROR_AUTH', 10002);
57
58 /** Error: No From: address has been provided */
59 define('PEAR_MAIL_SMTP_ERROR_FROM', 10003);
60
61 /** Error: Failed to set sender */
62 define('PEAR_MAIL_SMTP_ERROR_SENDER', 10004);
63
64 /** Error: Failed to add recipient */
65 define('PEAR_MAIL_SMTP_ERROR_RECIPIENT', 10005);
66
67 /** Error: Failed to send data */
68 define('PEAR_MAIL_SMTP_ERROR_DATA', 10006);
69
70 /**
71 * SMTP implementation of the PEAR Mail interface. Requires the Net_SMTP class.
72 * @access public
73 * @package Mail
74 * @version $Revision$
75 */
76 class Mail_smtp extends Mail {
77
78 /**
79 * SMTP connection object.
80 *
81 * @var object
82 * @access private
83 */
84 var $_smtp = null;
85
86 /**
87 * The list of service extension parameters to pass to the Net_SMTP
88 * mailFrom() command.
89 *
90 * @var array
91 */
92 var $_extparams = array();
93
94 /**
95 * The SMTP host to connect to.
96 *
97 * @var string
98 */
99 var $host = 'localhost';
100
101 /**
102 * The port the SMTP server is on.
103 *
104 * @var integer
105 */
106 var $port = 25;
107
108 /**
109 * Should STARTTLS connection be used?
110 *
111 * This value may be set to true or false.
112 *
113 * If the value is set to true, the Net_SMTP package will attempt to use
114 * a STARTTLS encrypted connection.
115 *
116 * If the value is set to false, the Net_SMTP package will avoid
117 * a STARTTLS encrypted connection.
118 *
119 * NULL indicates only STARTTLS if $auth is set.
120 *
121 * PEAR/Net_SMTP >= 1.10.0 required.
122 *
123 * @var boolean
124 */
125 var $starttls = null;
126
127 /**
128 * Should SMTP authentication be used?
129 *
130 * This value may be set to true, false or the name of a specific
131 * authentication method.
132 *
133 * If the value is set to true, the Net_SMTP package will attempt to use
134 * the best authentication method advertised by the remote SMTP server.
135 *
136 * @var mixed
137 */
138 var $auth = false;
139
140 /**
141 * The username to use if the SMTP server requires authentication.
142 *
143 * @var string
144 */
145 var $username = '';
146
147 /**
148 * The password to use if the SMTP server requires authentication.
149 *
150 * @var string
151 */
152 var $password = '';
153
154 /**
155 * Hostname or domain that will be sent to the remote SMTP server in the
156 * HELO / EHLO message.
157 *
158 * @var string
159 */
160 var $localhost = 'localhost';
161
162 /**
163 * SMTP connection timeout value. NULL indicates no timeout.
164 *
165 * @var integer
166 */
167 var $timeout = null;
168
169 /**
170 * Turn on Net_SMTP debugging?
171 *
172 * @var boolean $debug
173 */
174 var $debug = false;
175
176 /**
177 * Set debug_handler on Net_SMTP
178 *
179 * @var callable $debug_handler
180 */
181 var $debug_handler = null;
182
183 /**
184 * we need the greeting; from it we can extract the authorative name of the mail
185 * server we've really connected to. ideal if we're connecting to a round-robin
186 * of relay servers and need to track which exact one took the email
187 *
188 * @var string
189 */
190 var $greeting = null;
191
192 /**
193 * Indicates whether or not the SMTP connection should persist over
194 * multiple calls to the send() method.
195 *
196 * @var boolean
197 */
198 var $persist = false;
199
200 /**
201 * Use SMTP command pipelining (specified in RFC 2920) if the SMTP server
202 * supports it. This speeds up delivery over high-latency connections. By
203 * default, use the default value supplied by Net_SMTP.
204 *
205 * @var boolean
206 */
207 var $pipelining;
208
209 /**
210 * The list of socket options
211 *
212 * @var array
213 */
214 var $socket_options = array();
215
216 /**
217 * SMTP response message
218 *
219 * @var string
220 * @since 1.6.0
221 */
222 var $response = null;
223
224 /**
225 * If the message ends up in the queue, on the recipient server,
226 * the response will be saved here.
227 * Some successfully delivered emails will include a “queued”
228 * notation in the SMTP response, such as "250 OK; queued as 12345".
229 * This indicates that the email was delivered to the recipient
230 * as expected, but may require additional processing before it
231 * lands in the recipient’s inbox.
232 *
233 * @var string
234 */
235 var $queued_as = null;
236
237 /**
238 * Constructor.
239 *
240 * Instantiates a new Mail_smtp:: object based on the parameters
241 * passed in. It looks for the following parameters:
242 * host The server to connect to. Defaults to localhost.
243 * port The port to connect to. Defaults to 25.
244 * auth SMTP authentication. Defaults to none.
245 * starttls Should STARTTLS connection be used? No default. PEAR/Net_SMTP >= 1.10.0 required.
246 * username The username to use for SMTP auth. No default.
247 * password The password to use for SMTP auth. No default.
248 * localhost The local hostname / domain. Defaults to localhost.
249 * timeout The SMTP connection timeout. Defaults to none.
250 * verp Whether to use VERP or not. Defaults to false.
251 * DEPRECATED as of 1.2.0 (use setMailParams()).
252 * debug Activate SMTP debug mode? Defaults to false.
253 * debug_handler Set SMTP debug handler function. Defaults to null.
254 * persist Should the SMTP connection persist?
255 * pipelining Use SMTP command pipelining
256 * socket_options Socket stream_context_create() options.
257 *
258 * If a parameter is present in the $params array, it replaces the
259 * default.
260 *
261 * @param array Hash containing any parameters different from the
262 * defaults.
263 */
264 public function __construct($params)
265 {
266 if (isset($params['host'])) $this->host = $params['host'];
267 if (isset($params['port'])) $this->port = $params['port'];
268 if (isset($params['auth'])) $this->auth = $params['auth'];
269 if (isset($params['starttls'])) $this->starttls = $params['starttls'];
270 if (isset($params['username'])) $this->username = $params['username'];
271 if (isset($params['password'])) $this->password = $params['password'];
272 if (isset($params['localhost'])) $this->localhost = $params['localhost'];
273 if (isset($params['timeout'])) $this->timeout = $params['timeout'];
274 if (isset($params['debug'])) $this->debug = (bool)$params['debug'];
275 if (isset($params['debug_handler'])) $this->debug_handler = $params['debug_handler'];
276 if (isset($params['persist'])) $this->persist = (bool)$params['persist'];
277 if (isset($params['pipelining'])) $this->pipelining = (bool)$params['pipelining'];
278 if (isset($params['socket_options'])) $this->socket_options = $params['socket_options'];
279 // Deprecated options
280 if (isset($params['verp'])) {
281 $this->addServiceExtensionParameter('XVERP', is_bool($params['verp']) ? null : $params['verp']);
282 }
283 }
284
285 /**
286 * Destructor implementation to ensure that we disconnect from any
287 * potentially-alive persistent SMTP connections.
288 */
289 public function __destruct()
290 {
291 $this->disconnect();
292 }
293
294 /**
295 * Implements Mail::send() function using SMTP.
296 *
297 * @param mixed $recipients Either a comma-seperated list of recipients
298 * (RFC822 compliant), or an array of recipients,
299 * each RFC822 valid. This may contain recipients not
300 * specified in the headers, for Bcc:, resending
301 * messages, etc.
302 *
303 * @param array $headers The array of headers to send with the mail, in an
304 * associative array, where the array key is the
305 * header name (e.g., 'Subject'), and the array value
306 * is the header value (e.g., 'test'). The header
307 * produced from those values would be 'Subject:
308 * test'.
309 *
310 * @param string $body The full text of the message body, including any
311 * MIME parts, etc.
312 *
313 * @return mixed Returns true on success, or a PEAR_Error
314 * containing a descriptive error message on
315 * failure.
316 */
317 public function send($recipients, $headers, $body)
318 {
319 $result = $this->send_or_fail($recipients, $headers, $body);
320
321 /* If persistent connections are disabled, destroy our SMTP object. */
322 if ($this->persist === false) {
323 $this->disconnect();
324 }
325
326 return $result;
327 }
328
329 protected function send_or_fail($recipients, $headers, $body)
330 {
331 /* If we don't already have an SMTP object, create one. */
332 $result = $this->getSMTPObject();
333 if (PEAR::isError($result)) {
334 return $result;
335 }
336
337 if (!is_array($headers)) {
338 return PEAR::raiseError('$headers must be an array');
339 }
340
341 $this->_sanitizeHeaders($headers);
342
343 $headerElements = $this->prepareHeaders($headers);
344 if (is_a($headerElements, 'PEAR_Error')) {
345 $this->_smtp->rset();
346 return $headerElements;
347 }
348 list($from, $textHeaders) = $headerElements;
349
350 /* Since few MTAs are going to allow this header to be forged
351 * unless it's in the MAIL FROM: exchange, we'll use
352 * Return-Path instead of From: if it's set. */
353 if (!empty($headers['Return-Path'])) {
354 $from = $headers['Return-Path'];
355 }
356
357 if (!isset($from)) {
358 $this->_smtp->rset();
359 return PEAR::raiseError('No From: address has been provided',
360 PEAR_MAIL_SMTP_ERROR_FROM);
361 }
362
363 $params = '';
364 if (!empty($this->_extparams)) {
365 foreach ($this->_extparams as $key => $val) {
366 $params .= ' ' . $key . (is_null($val) ? '' : '=' . $val);
367 }
368 }
369 if (PEAR::isError($res = $this->_smtp->mailFrom($from, ltrim($params)))) {
370 $error = $this->_error("Failed to set sender: $from", $res);
371 $this->_smtp->rset();
372 return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_SENDER);
373 }
374
375 $recipients = $this->parseRecipients($recipients);
376 if (is_a($recipients, 'PEAR_Error')) {
377 $this->_smtp->rset();
378 return $recipients;
379 }
380
381 foreach ($recipients as $recipient) {
382 $res = $this->_smtp->rcptTo($recipient);
383 if (is_a($res, 'PEAR_Error')) {
384 $error = $this->_error("Failed to add recipient: $recipient", $res);
385 $this->_smtp->rset();
386 return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_RECIPIENT);
387 }
388 }
389
390 /* Send the message's headers and the body as SMTP data. */
391 $res = $this->_smtp->data($body, $textHeaders);
392
393 list($code, $args) = $this->_smtp->getResponse();
394
395 $this->response = $code . ' ' . $args;
396
397 if (preg_match("/ queued as (.*)/", $args, $queued)) {
398 $this->queued_as = $queued[1];
399 }
400
401 /* we need the greeting; from it we can extract the authorative name of the mail server we've really connected to.
402 * ideal if we're connecting to a round-robin of relay servers and need to track which exact one took the email */
403 $this->greeting = $this->_smtp->getGreeting();
404
405 if (is_a($res, 'PEAR_Error')) {
406 $error = $this->_error('Failed to send data', $res);
407 $this->_smtp->rset();
408 return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_DATA);
409 }
410
411 return true;
412 }
413
414 /**
415 * Connect to the SMTP server by instantiating a Net_SMTP object.
416 *
417 * @return mixed Returns a reference to the Net_SMTP object on success, or
418 * a PEAR_Error containing a descriptive error message on
419 * failure.
420 *
421 * @since 1.2.0
422 */
423 public function getSMTPObject()
424 {
425 if (is_object($this->_smtp) !== false) {
426 return $this->_smtp;
427 }
428
429 include_once 'Net/SMTP.php';
430 $this->_smtp = new Net_SMTP($this->host,
431 $this->port,
432 $this->localhost,
433 $this->pipelining,
434 0,
435 $this->socket_options);
436
437 /* If we still don't have an SMTP object at this point, fail. */
438 if (is_object($this->_smtp) === false) {
439 return PEAR::raiseError('Failed to create a Net_SMTP object',
440 PEAR_MAIL_SMTP_ERROR_CREATE);
441 }
442
443 /* Configure the SMTP connection. */
444 if ($this->debug) {
445 $this->_smtp->setDebug(true, $this->debug_handler);
446 }
447
448 /* Attempt to connect to the configured SMTP server. */
449 if (PEAR::isError($res = $this->_smtp->connect($this->timeout))) {
450 $error = $this->_error('Failed to connect to ' .
451 $this->host . ':' . $this->port,
452 $res);
453 return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_CONNECT);
454 }
455
456 /* Attempt to authenticate if authentication has been enabled. */
457 if ($this->auth) {
458 $method = is_string($this->auth) ? $this->auth : '';
459
460 $tls = $this->starttls === false ? false : true;
461
462 if (PEAR::isError($res = $this->_smtp->auth($this->username,
463 $this->password,
464 $method,
465 $tls))) {
466 $error = $this->_error("$method authentication failure",
467 $res);
468 $this->_smtp->rset();
469 return PEAR::raiseError($error, PEAR_MAIL_SMTP_ERROR_AUTH);
470 }
471 }
472
473 /* Attempt to establish a TLS encrypted connection. PEAR/Net_SMTP >= 1.10.0 required. */
474 if ($this->starttls && !$this->auth) {
475 $starttls = $this->_smtp->starttls();
476 if (PEAR::isError($starttls)) {
477 return PEAR::raiseError($starttls);
478 } elseif ($starttls === false) {
479 return PEAR::raiseError('STARTTLS failed');
480 }
481 }
482
483 return $this->_smtp;
484 }
485
486 /**
487 * Add parameter associated with a SMTP service extension.
488 *
489 * @param string Extension keyword.
490 * @param string Any value the keyword needs.
491 *
492 * @since 1.2.0
493 */
494 public function addServiceExtensionParameter($keyword, $value = null)
495 {
496 $this->_extparams[$keyword] = $value;
497 }
498
499 /**
500 * Disconnect and destroy the current SMTP connection.
501 *
502 * @return boolean True if the SMTP connection no longer exists.
503 *
504 * @since 1.1.9
505 */
506 public function disconnect()
507 {
508 /* If we have an SMTP object, disconnect and destroy it. */
509 if (is_object($this->_smtp) && $this->_smtp->disconnect()) {
510 $this->_smtp = null;
511 }
512
513 /* We are disconnected if we no longer have an SMTP object. */
514 return ($this->_smtp === null);
515 }
516
517 /**
518 * Returns the SMTP response message after sending.
519 *
520 * @return string SMTP response message or NULL.
521 *
522 * @since 1.6.0
523 */
524 public function getResponse()
525 {
526 return $this->response;
527 }
528
529 /**
530 * Returns the SMTP response message if includes "queue" after sending.
531 *
532 * @return string SMTP queue message or NULL.
533 *
534 * @since 1.6.0
535 */
536 public function getQueuedAs()
537 {
538 return $this->queued_as;
539 }
540
541 /**
542 * Build a standardized string describing the current SMTP error.
543 *
544 * @param string $text Custom string describing the error context.
545 * @param object $error Reference to the current PEAR_Error object.
546 *
547 * @return string A string describing the current SMTP error.
548 *
549 * @since 1.1.7
550 */
551 protected function _error($text, $error)
552 {
553 /* Split the SMTP response into a code and a response string. */
554 list($code, $response) = $this->_smtp->getResponse();
555
556 /* Build our standardized error string. */
557 return $text
558 . ' [SMTP: ' . $error->getMessage()
559 . " (code: $code, response: $response)]";
560 }
561
562 }