PageRenderTime 62ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/PHPMailer/class.phpmailer.php

https://bitbucket.org/haps/c3s-php
PHP | 3689 lines | 2177 code | 232 blank | 1280 comment | 355 complexity | 3879f493740e16e3906cad9a1c831789 MD5 | raw file
Possible License(s): LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * PHPMailer - PHP email creation and transport class.
  4. * PHP Version 5
  5. * @package PHPMailer
  6. * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
  7. * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  8. * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  9. * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  10. * @author Brent R. Matzelle (original founder)
  11. * @copyright 2012 - 2014 Marcus Bointon
  12. * @copyright 2010 - 2012 Jim Jagielski
  13. * @copyright 2004 - 2009 Andy Prevost
  14. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  15. * @note This program is distributed in the hope that it will be useful - WITHOUT
  16. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  17. * FITNESS FOR A PARTICULAR PURPOSE.
  18. */
  19. /**
  20. * PHPMailer - PHP email creation and transport class.
  21. * @package PHPMailer
  22. * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  23. * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  24. * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  25. * @author Brent R. Matzelle (original founder)
  26. */
  27. class PHPMailer
  28. {
  29. /**
  30. * The PHPMailer Version number.
  31. * @type string
  32. */
  33. public $Version = '5.2.10';
  34. /**
  35. * Email priority.
  36. * Options: null (default), 1 = High, 3 = Normal, 5 = low.
  37. * When null, the header is not set at all.
  38. * @type integer
  39. */
  40. public $Priority = null;
  41. /**
  42. * The character set of the message.
  43. * @type string
  44. */
  45. public $CharSet = 'iso-8859-1';
  46. /**
  47. * The MIME Content-type of the message.
  48. * @type string
  49. */
  50. public $ContentType = 'text/plain';
  51. /**
  52. * The message encoding.
  53. * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
  54. * @type string
  55. */
  56. public $Encoding = '8bit';
  57. /**
  58. * Holds the most recent mailer error message.
  59. * @type string
  60. */
  61. public $ErrorInfo = '';
  62. /**
  63. * The From email address for the message.
  64. * @type string
  65. */
  66. public $From = 'root@localhost';
  67. /**
  68. * The From name of the message.
  69. * @type string
  70. */
  71. public $FromName = 'Root User';
  72. /**
  73. * The Sender email (Return-Path) of the message.
  74. * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  75. * @type string
  76. */
  77. public $Sender = '';
  78. /**
  79. * The Return-Path of the message.
  80. * If empty, it will be set to either From or Sender.
  81. * @type string
  82. * @deprecated Email senders should never set a return-path header;
  83. * it's the receiver's job (RFC5321 section 4.4), so this no longer does anything.
  84. * @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference
  85. */
  86. public $ReturnPath = '';
  87. /**
  88. * The Subject of the message.
  89. * @type string
  90. */
  91. public $Subject = '';
  92. /**
  93. * An HTML or plain text message body.
  94. * If HTML then call isHTML(true).
  95. * @type string
  96. */
  97. public $Body = '';
  98. /**
  99. * The plain-text message body.
  100. * This body can be read by mail clients that do not have HTML email
  101. * capability such as mutt & Eudora.
  102. * Clients that can read HTML will view the normal Body.
  103. * @type string
  104. */
  105. public $AltBody = '';
  106. /**
  107. * An iCal message part body.
  108. * Only supported in simple alt or alt_inline message types
  109. * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator
  110. * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
  111. * @link http://kigkonsult.se/iCalcreator/
  112. * @type string
  113. */
  114. public $Ical = '';
  115. /**
  116. * The complete compiled MIME message body.
  117. * @access protected
  118. * @type string
  119. */
  120. protected $MIMEBody = '';
  121. /**
  122. * The complete compiled MIME message headers.
  123. * @type string
  124. * @access protected
  125. */
  126. protected $MIMEHeader = '';
  127. /**
  128. * Extra headers that createHeader() doesn't fold in.
  129. * @type string
  130. * @access protected
  131. */
  132. protected $mailHeader = '';
  133. /**
  134. * Word-wrap the message body to this number of chars.
  135. * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
  136. * @type integer
  137. */
  138. public $WordWrap = 0;
  139. /**
  140. * Which method to use to send mail.
  141. * Options: "mail", "sendmail", or "smtp".
  142. * @type string
  143. */
  144. public $Mailer = 'mail';
  145. /**
  146. * The path to the sendmail program.
  147. * @type string
  148. */
  149. public $Sendmail = '/usr/sbin/sendmail';
  150. /**
  151. * Whether mail() uses a fully sendmail-compatible MTA.
  152. * One which supports sendmail's "-oi -f" options.
  153. * @type boolean
  154. */
  155. public $UseSendmailOptions = true;
  156. /**
  157. * Path to PHPMailer plugins.
  158. * Useful if the SMTP class is not in the PHP include path.
  159. * @type string
  160. * @deprecated Should not be needed now there is an autoloader.
  161. */
  162. public $PluginDir = '';
  163. /**
  164. * The email address that a reading confirmation should be sent to.
  165. * @type string
  166. */
  167. public $ConfirmReadingTo = '';
  168. /**
  169. * The hostname to use in Message-Id and Received headers
  170. * and as default HELO string.
  171. * If empty, the value returned
  172. * by SERVER_NAME is used or 'localhost.localdomain'.
  173. * @type string
  174. */
  175. public $Hostname = '';
  176. /**
  177. * An ID to be used in the Message-Id header.
  178. * If empty, a unique id will be generated.
  179. * @type string
  180. */
  181. public $MessageID = '';
  182. /**
  183. * The message Date to be used in the Date header.
  184. * If empty, the current date will be added.
  185. * @type string
  186. */
  187. public $MessageDate = '';
  188. /**
  189. * SMTP hosts.
  190. * Either a single hostname or multiple semicolon-delimited hostnames.
  191. * You can also specify a different port
  192. * for each host by using this format: [hostname:port]
  193. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  194. * You can also specify encryption type, for example:
  195. * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
  196. * Hosts will be tried in order.
  197. * @type string
  198. */
  199. public $Host = 'localhost';
  200. /**
  201. * The default SMTP server port.
  202. * @type integer
  203. * @TODO Why is this needed when the SMTP class takes care of it?
  204. */
  205. public $Port = 25;
  206. /**
  207. * The SMTP HELO of the message.
  208. * Default is $Hostname.
  209. * @type string
  210. * @see PHPMailer::$Hostname
  211. */
  212. public $Helo = '';
  213. /**
  214. * What kind of encryption to use on the SMTP connection.
  215. * Options: '', 'ssl' or 'tls'
  216. * @type string
  217. */
  218. public $SMTPSecure = '';
  219. /**
  220. * Whether to enable TLS encryption automatically if a server supports it,
  221. * even if `SMTPSecure` is not set to 'tls'.
  222. * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
  223. * @type boolean
  224. */
  225. public $SMTPAutoTLS = true;
  226. /**
  227. * Whether to use SMTP authentication.
  228. * Uses the Username and Password properties.
  229. * @type boolean
  230. * @see PHPMailer::$Username
  231. * @see PHPMailer::$Password
  232. */
  233. public $SMTPAuth = false;
  234. /**
  235. * Options array passed to stream_context_create when connecting via SMTP.
  236. * @type array
  237. */
  238. public $SMTPOptions = array();
  239. /**
  240. * SMTP username.
  241. * @type string
  242. */
  243. public $Username = '';
  244. /**
  245. * SMTP password.
  246. * @type string
  247. */
  248. public $Password = '';
  249. /**
  250. * SMTP auth type.
  251. * Options are LOGIN (default), PLAIN, NTLM, CRAM-MD5
  252. * @type string
  253. */
  254. public $AuthType = '';
  255. /**
  256. * SMTP realm.
  257. * Used for NTLM auth
  258. * @type string
  259. */
  260. public $Realm = '';
  261. /**
  262. * SMTP workstation.
  263. * Used for NTLM auth
  264. * @type string
  265. */
  266. public $Workstation = '';
  267. /**
  268. * The SMTP server timeout in seconds.
  269. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
  270. * @type integer
  271. */
  272. public $Timeout = 300;
  273. /**
  274. * SMTP class debug output mode.
  275. * Debug output level.
  276. * Options:
  277. * * `0` No output
  278. * * `1` Commands
  279. * * `2` Data and commands
  280. * * `3` As 2 plus connection status
  281. * * `4` Low-level data output
  282. * @type integer
  283. * @see SMTP::$do_debug
  284. */
  285. public $SMTPDebug = 0;
  286. /**
  287. * How to handle debug output.
  288. * Options:
  289. * * `echo` Output plain-text as-is, appropriate for CLI
  290. * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
  291. * * `error_log` Output to error log as configured in php.ini
  292. *
  293. * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
  294. * <code>
  295. * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
  296. * </code>
  297. * @type string|callable
  298. * @see SMTP::$Debugoutput
  299. */
  300. public $Debugoutput = 'echo';
  301. /**
  302. * Whether to keep SMTP connection open after each message.
  303. * If this is set to true then to close the connection
  304. * requires an explicit call to smtpClose().
  305. * @type boolean
  306. */
  307. public $SMTPKeepAlive = false;
  308. /**
  309. * Whether to split multiple to addresses into multiple messages
  310. * or send them all in one message.
  311. * @type boolean
  312. */
  313. public $SingleTo = false;
  314. /**
  315. * Storage for addresses when SingleTo is enabled.
  316. * @type array
  317. * @TODO This should really not be public
  318. */
  319. public $SingleToArray = array();
  320. /**
  321. * Whether to generate VERP addresses on send.
  322. * Only applicable when sending via SMTP.
  323. * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
  324. * @link http://www.postfix.org/VERP_README.html Postfix VERP info
  325. * @type boolean
  326. */
  327. public $do_verp = false;
  328. /**
  329. * Whether to allow sending messages with an empty body.
  330. * @type boolean
  331. */
  332. public $AllowEmpty = false;
  333. /**
  334. * The default line ending.
  335. * @note The default remains "\n". We force CRLF where we know
  336. * it must be used via self::CRLF.
  337. * @type string
  338. */
  339. public $LE = "\n";
  340. /**
  341. * DKIM selector.
  342. * @type string
  343. */
  344. public $DKIM_selector = '';
  345. /**
  346. * DKIM Identity.
  347. * Usually the email address used as the source of the email
  348. * @type string
  349. */
  350. public $DKIM_identity = '';
  351. /**
  352. * DKIM passphrase.
  353. * Used if your key is encrypted.
  354. * @type string
  355. */
  356. public $DKIM_passphrase = '';
  357. /**
  358. * DKIM signing domain name.
  359. * @example 'example.com'
  360. * @type string
  361. */
  362. public $DKIM_domain = '';
  363. /**
  364. * DKIM private key file path.
  365. * @type string
  366. */
  367. public $DKIM_private = '';
  368. /**
  369. * Callback Action function name.
  370. *
  371. * The function that handles the result of the send email action.
  372. * It is called out by send() for each email sent.
  373. *
  374. * Value can be any php callable: http://www.php.net/is_callable
  375. *
  376. * Parameters:
  377. * boolean $result result of the send action
  378. * string $to email address of the recipient
  379. * string $cc cc email addresses
  380. * string $bcc bcc email addresses
  381. * string $subject the subject
  382. * string $body the email body
  383. * string $from email address of sender
  384. * @type string
  385. */
  386. public $action_function = '';
  387. /**
  388. * What to put in the X-Mailer header.
  389. * Options: An empty string for PHPMailer default, whitespace for none, or a string to use
  390. * @type string
  391. */
  392. public $XMailer = '';
  393. /**
  394. * An instance of the SMTP sender class.
  395. * @type SMTP
  396. * @access protected
  397. */
  398. protected $smtp = null;
  399. /**
  400. * The array of 'to' addresses.
  401. * @type array
  402. * @access protected
  403. */
  404. protected $to = array();
  405. /**
  406. * The array of 'cc' addresses.
  407. * @type array
  408. * @access protected
  409. */
  410. protected $cc = array();
  411. /**
  412. * The array of 'bcc' addresses.
  413. * @type array
  414. * @access protected
  415. */
  416. protected $bcc = array();
  417. /**
  418. * The array of reply-to names and addresses.
  419. * @type array
  420. * @access protected
  421. */
  422. protected $ReplyTo = array();
  423. /**
  424. * An array of all kinds of addresses.
  425. * Includes all of $to, $cc, $bcc
  426. * @type array
  427. * @access protected
  428. */
  429. protected $all_recipients = array();
  430. /**
  431. * The array of attachments.
  432. * @type array
  433. * @access protected
  434. */
  435. protected $attachment = array();
  436. /**
  437. * The array of custom headers.
  438. * @type array
  439. * @access protected
  440. */
  441. protected $CustomHeader = array();
  442. /**
  443. * The most recent Message-ID (including angular brackets).
  444. * @type string
  445. * @access protected
  446. */
  447. protected $lastMessageID = '';
  448. /**
  449. * The message's MIME type.
  450. * @type string
  451. * @access protected
  452. */
  453. protected $message_type = '';
  454. /**
  455. * The array of MIME boundary strings.
  456. * @type array
  457. * @access protected
  458. */
  459. protected $boundary = array();
  460. /**
  461. * The array of available languages.
  462. * @type array
  463. * @access protected
  464. */
  465. protected $language = array();
  466. /**
  467. * The number of errors encountered.
  468. * @type integer
  469. * @access protected
  470. */
  471. protected $error_count = 0;
  472. /**
  473. * The S/MIME certificate file path.
  474. * @type string
  475. * @access protected
  476. */
  477. protected $sign_cert_file = '';
  478. /**
  479. * The S/MIME key file path.
  480. * @type string
  481. * @access protected
  482. */
  483. protected $sign_key_file = '';
  484. /**
  485. * The optional S/MIME extra certificates ("CA Chain") file path.
  486. * @type string
  487. * @access protected
  488. */
  489. protected $sign_extracerts_file = '';
  490. /**
  491. * The S/MIME password for the key.
  492. * Used only if the key is encrypted.
  493. * @type string
  494. * @access protected
  495. */
  496. protected $sign_key_pass = '';
  497. /**
  498. * Whether to throw exceptions for errors.
  499. * @type boolean
  500. * @access protected
  501. */
  502. protected $exceptions = false;
  503. /**
  504. * Unique ID used for message ID and boundaries.
  505. * @type string
  506. * @access protected
  507. */
  508. protected $uniqueid = '';
  509. /**
  510. * Error severity: message only, continue processing.
  511. */
  512. const STOP_MESSAGE = 0;
  513. /**
  514. * Error severity: message, likely ok to continue processing.
  515. */
  516. const STOP_CONTINUE = 1;
  517. /**
  518. * Error severity: message, plus full stop, critical error reached.
  519. */
  520. const STOP_CRITICAL = 2;
  521. /**
  522. * SMTP RFC standard line ending.
  523. */
  524. const CRLF = "\r\n";
  525. /**
  526. * The maximum line length allowed by RFC 2822 section 2.1.1
  527. * @type integer
  528. */
  529. const MAX_LINE_LENGTH = 998;
  530. /**
  531. * Constructor.
  532. * @param boolean $exceptions Should we throw external exceptions?
  533. */
  534. public function __construct($exceptions = false)
  535. {
  536. $this->exceptions = (boolean)$exceptions;
  537. }
  538. /**
  539. * Destructor.
  540. */
  541. public function __destruct()
  542. {
  543. //Close any open SMTP connection nicely
  544. if ($this->Mailer == 'smtp') {
  545. $this->smtpClose();
  546. }
  547. }
  548. /**
  549. * Call mail() in a safe_mode-aware fashion.
  550. * Also, unless sendmail_path points to sendmail (or something that
  551. * claims to be sendmail), don't pass params (not a perfect fix,
  552. * but it will do)
  553. * @param string $to To
  554. * @param string $subject Subject
  555. * @param string $body Message Body
  556. * @param string $header Additional Header(s)
  557. * @param string $params Params
  558. * @access private
  559. * @return boolean
  560. */
  561. private function mailPassthru($to, $subject, $body, $header, $params)
  562. {
  563. //Check overloading of mail function to avoid double-encoding
  564. if (ini_get('mbstring.func_overload') & 1) {
  565. $subject = $this->secureHeader($subject);
  566. } else {
  567. $subject = $this->encodeHeader($this->secureHeader($subject));
  568. }
  569. if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {
  570. $result = @mail($to, $subject, $body, $header);
  571. } else {
  572. $result = @mail($to, $subject, $body, $header, $params);
  573. }
  574. return $result;
  575. }
  576. /**
  577. * Output debugging info via user-defined method.
  578. * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
  579. * @see PHPMailer::$Debugoutput
  580. * @see PHPMailer::$SMTPDebug
  581. * @param string $str
  582. */
  583. protected function edebug($str)
  584. {
  585. if ($this->SMTPDebug <= 0) {
  586. return;
  587. }
  588. //Avoid clash with built-in function names
  589. if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
  590. call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
  591. return;
  592. }
  593. switch ($this->Debugoutput) {
  594. case 'error_log':
  595. //Don't output, just log
  596. error_log($str);
  597. break;
  598. case 'html':
  599. //Cleans up output a bit for a better looking, HTML-safe output
  600. echo htmlentities(
  601. preg_replace('/[\r\n]+/', '', $str),
  602. ENT_QUOTES,
  603. 'UTF-8'
  604. )
  605. . "<br>\n";
  606. break;
  607. case 'echo':
  608. default:
  609. //Normalize line breaks
  610. $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
  611. echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
  612. "\n",
  613. "\n \t ",
  614. trim($str)
  615. ) . "\n";
  616. }
  617. }
  618. /**
  619. * Sets message type to HTML or plain.
  620. * @param boolean $isHtml True for HTML mode.
  621. * @return void
  622. */
  623. public function isHTML($isHtml = true)
  624. {
  625. if ($isHtml) {
  626. $this->ContentType = 'text/html';
  627. } else {
  628. $this->ContentType = 'text/plain';
  629. }
  630. }
  631. /**
  632. * Send messages using SMTP.
  633. * @return void
  634. */
  635. public function isSMTP()
  636. {
  637. $this->Mailer = 'smtp';
  638. }
  639. /**
  640. * Send messages using PHP's mail() function.
  641. * @return void
  642. */
  643. public function isMail()
  644. {
  645. $this->Mailer = 'mail';
  646. }
  647. /**
  648. * Send messages using $Sendmail.
  649. * @return void
  650. */
  651. public function isSendmail()
  652. {
  653. $ini_sendmail_path = ini_get('sendmail_path');
  654. if (!stristr($ini_sendmail_path, 'sendmail')) {
  655. $this->Sendmail = '/usr/sbin/sendmail';
  656. } else {
  657. $this->Sendmail = $ini_sendmail_path;
  658. }
  659. $this->Mailer = 'sendmail';
  660. }
  661. /**
  662. * Send messages using qmail.
  663. * @return void
  664. */
  665. public function isQmail()
  666. {
  667. $ini_sendmail_path = ini_get('sendmail_path');
  668. if (!stristr($ini_sendmail_path, 'qmail')) {
  669. $this->Sendmail = '/var/qmail/bin/qmail-inject';
  670. } else {
  671. $this->Sendmail = $ini_sendmail_path;
  672. }
  673. $this->Mailer = 'qmail';
  674. }
  675. /**
  676. * Add a "To" address.
  677. * @param string $address
  678. * @param string $name
  679. * @return boolean true on success, false if address already used
  680. */
  681. public function addAddress($address, $name = '')
  682. {
  683. return $this->addAnAddress('to', $address, $name);
  684. }
  685. /**
  686. * Add a "CC" address.
  687. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
  688. * @param string $address
  689. * @param string $name
  690. * @return boolean true on success, false if address already used
  691. */
  692. public function addCC($address, $name = '')
  693. {
  694. return $this->addAnAddress('cc', $address, $name);
  695. }
  696. /**
  697. * Add a "BCC" address.
  698. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
  699. * @param string $address
  700. * @param string $name
  701. * @return boolean true on success, false if address already used
  702. */
  703. public function addBCC($address, $name = '')
  704. {
  705. return $this->addAnAddress('bcc', $address, $name);
  706. }
  707. /**
  708. * Add a "Reply-to" address.
  709. * @param string $address
  710. * @param string $name
  711. * @return boolean
  712. */
  713. public function addReplyTo($address, $name = '')
  714. {
  715. return $this->addAnAddress('Reply-To', $address, $name);
  716. }
  717. /**
  718. * Add an address to one of the recipient arrays.
  719. * Addresses that have been added already return false, but do not throw exceptions
  720. * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
  721. * @param string $address The email address to send to
  722. * @param string $name
  723. * @throws phpmailerException
  724. * @return boolean true on success, false if address already used or invalid in some way
  725. * @access protected
  726. */
  727. protected function addAnAddress($kind, $address, $name = '')
  728. {
  729. if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
  730. $this->setError($this->lang('Invalid recipient array') . ': ' . $kind);
  731. $this->edebug($this->lang('Invalid recipient array') . ': ' . $kind);
  732. if ($this->exceptions) {
  733. throw new phpmailerException('Invalid recipient array: ' . $kind);
  734. }
  735. return false;
  736. }
  737. $address = trim($address);
  738. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  739. if (!$this->validateAddress($address)) {
  740. $this->setError($this->lang('invalid_address') . ': ' . $address);
  741. $this->edebug($this->lang('invalid_address') . ': ' . $address);
  742. if ($this->exceptions) {
  743. throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
  744. }
  745. return false;
  746. }
  747. if ($kind != 'Reply-To') {
  748. if (!isset($this->all_recipients[strtolower($address)])) {
  749. array_push($this->$kind, array($address, $name));
  750. $this->all_recipients[strtolower($address)] = true;
  751. return true;
  752. }
  753. } else {
  754. if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  755. $this->ReplyTo[strtolower($address)] = array($address, $name);
  756. return true;
  757. }
  758. }
  759. return false;
  760. }
  761. /**
  762. * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
  763. * of the form "display name <address>" into an array of name/address pairs.
  764. * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
  765. * Note that quotes in the name part are removed.
  766. * @param string $addrstr The address list string
  767. * @param bool $useimap Whether to use the IMAP extension to parse the list
  768. * @return array
  769. * @link http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
  770. */
  771. public function parseAddresses($addrstr, $useimap = true)
  772. {
  773. $addresses = array();
  774. if ($useimap and function_exists('imap_rfc822_parse_adrlist')) {
  775. //Use this built-in parser if it's available
  776. $list = imap_rfc822_parse_adrlist($addrstr, '');
  777. foreach ($list as $address) {
  778. if ($address->host != '.SYNTAX-ERROR.') {
  779. if ($this->validateAddress($address->mailbox . '@' . $address->host)) {
  780. $addresses[] = array(
  781. 'name' => (property_exists($address, 'personal') ? $address->personal : ''),
  782. 'address' => $address->mailbox . '@' . $address->host
  783. );
  784. }
  785. }
  786. }
  787. } else {
  788. //Use this simpler parser
  789. $list = explode(',', $addrstr);
  790. foreach ($list as $address) {
  791. $address = trim($address);
  792. //Is there a separate name part?
  793. if (strpos($address, '<') === false) {
  794. //No separate name, just use the whole thing
  795. if ($this->validateAddress($address)) {
  796. $addresses[] = array(
  797. 'name' => '',
  798. 'address' => $address
  799. );
  800. }
  801. } else {
  802. list($name, $email) = explode('<', $address);
  803. $email = trim(str_replace('>', '', $email));
  804. if ($this->validateAddress($email)) {
  805. $addresses[] = array(
  806. 'name' => trim(str_replace(array('"', "'"), '', $name)),
  807. 'address' => $email
  808. );
  809. }
  810. }
  811. }
  812. }
  813. return $addresses;
  814. }
  815. /**
  816. * Set the From and FromName properties.
  817. * @param string $address
  818. * @param string $name
  819. * @param boolean $auto Whether to also set the Sender address, defaults to true
  820. * @throws phpmailerException
  821. * @return boolean
  822. */
  823. public function setFrom($address, $name = '', $auto = true)
  824. {
  825. $address = trim($address);
  826. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  827. if (!$this->validateAddress($address)) {
  828. $this->setError($this->lang('invalid_address') . ': ' . $address);
  829. $this->edebug($this->lang('invalid_address') . ': ' . $address);
  830. if ($this->exceptions) {
  831. throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
  832. }
  833. return false;
  834. }
  835. $this->From = $address;
  836. $this->FromName = $name;
  837. if ($auto) {
  838. if (empty($this->Sender)) {
  839. $this->Sender = $address;
  840. }
  841. }
  842. return true;
  843. }
  844. /**
  845. * Return the Message-ID header of the last email.
  846. * Technically this is the value from the last time the headers were created,
  847. * but it's also the message ID of the last sent message except in
  848. * pathological cases.
  849. * @return string
  850. */
  851. public function getLastMessageID()
  852. {
  853. return $this->lastMessageID;
  854. }
  855. /**
  856. * Check that a string looks like an email address.
  857. * @param string $address The email address to check
  858. * @param string $patternselect A selector for the validation pattern to use :
  859. * * `auto` Pick strictest one automatically;
  860. * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
  861. * * `pcre` Use old PCRE implementation;
  862. * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; same as pcre8 but does not allow 'dotless' domains;
  863. * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
  864. * * `noregex` Don't use a regex: super fast, really dumb.
  865. * @return boolean
  866. * @static
  867. * @access public
  868. */
  869. public static function validateAddress($address, $patternselect = 'auto')
  870. {
  871. if (!$patternselect or $patternselect == 'auto') {
  872. //Check this constant first so it works when extension_loaded() is disabled by safe mode
  873. //Constant was added in PHP 5.2.4
  874. if (defined('PCRE_VERSION')) {
  875. //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2
  876. if (version_compare(PCRE_VERSION, '8.0.3') >= 0) {
  877. $patternselect = 'pcre8';
  878. } else {
  879. $patternselect = 'pcre';
  880. }
  881. } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) {
  882. //Fall back to older PCRE
  883. $patternselect = 'pcre';
  884. } else {
  885. //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
  886. if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
  887. $patternselect = 'php';
  888. } else {
  889. $patternselect = 'noregex';
  890. }
  891. }
  892. }
  893. switch ($patternselect) {
  894. case 'pcre8':
  895. /**
  896. * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains.
  897. * @link http://squiloople.com/2009/12/20/email-address-validation/
  898. * @copyright 2009-2010 Michael Rushton
  899. * Feel free to use and redistribute this code. But please keep this copyright notice.
  900. */
  901. return (boolean)preg_match(
  902. '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
  903. '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
  904. '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
  905. '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
  906. '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
  907. '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
  908. '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
  909. '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  910. '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
  911. $address
  912. );
  913. case 'pcre':
  914. //An older regex that doesn't need a recent PCRE
  915. return (boolean)preg_match(
  916. '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
  917. '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
  918. '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
  919. '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
  920. '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
  921. '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
  922. '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
  923. '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
  924. '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  925. '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
  926. $address
  927. );
  928. case 'html5':
  929. /**
  930. * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
  931. * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
  932. */
  933. return (boolean)preg_match(
  934. '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
  935. '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
  936. $address
  937. );
  938. case 'noregex':
  939. //No PCRE! Do something _very_ approximate!
  940. //Check the address is 3 chars or longer and contains an @ that's not the first or last char
  941. return (strlen($address) >= 3
  942. and strpos($address, '@') >= 1
  943. and strpos($address, '@') != strlen($address) - 1);
  944. case 'php':
  945. default:
  946. return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
  947. }
  948. }
  949. /**
  950. * Create a message and send it.
  951. * Uses the sending method specified by $Mailer.
  952. * @throws phpmailerException
  953. * @return boolean false on error - See the ErrorInfo property for details of the error.
  954. */
  955. public function send()
  956. {
  957. try {
  958. if (!$this->preSend()) {
  959. return false;
  960. }
  961. return $this->postSend();
  962. } catch (phpmailerException $exc) {
  963. $this->mailHeader = '';
  964. $this->setError($exc->getMessage());
  965. if ($this->exceptions) {
  966. throw $exc;
  967. }
  968. return false;
  969. }
  970. }
  971. /**
  972. * Prepare a message for sending.
  973. * @throws phpmailerException
  974. * @return boolean
  975. */
  976. public function preSend()
  977. {
  978. try {
  979. $this->mailHeader = '';
  980. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  981. throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
  982. }
  983. // Set whether the message is multipart/alternative
  984. if (!empty($this->AltBody)) {
  985. $this->ContentType = 'multipart/alternative';
  986. }
  987. $this->error_count = 0; // Reset errors
  988. $this->setMessageType();
  989. // Refuse to send an empty message unless we are specifically allowing it
  990. if (!$this->AllowEmpty and empty($this->Body)) {
  991. throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
  992. }
  993. // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
  994. $this->MIMEHeader = '';
  995. $this->MIMEBody = $this->createBody();
  996. // createBody may have added some headers, so retain them
  997. $tempheaders = $this->MIMEHeader;
  998. $this->MIMEHeader = $this->createHeader();
  999. $this->MIMEHeader .= $tempheaders;
  1000. // To capture the complete message when using mail(), create
  1001. // an extra header list which createHeader() doesn't fold in
  1002. if ($this->Mailer == 'mail') {
  1003. if (count($this->to) > 0) {
  1004. $this->mailHeader .= $this->addrAppend('To', $this->to);
  1005. } else {
  1006. $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
  1007. }
  1008. $this->mailHeader .= $this->headerLine(
  1009. 'Subject',
  1010. $this->encodeHeader($this->secureHeader(trim($this->Subject)))
  1011. );
  1012. }
  1013. // Sign with DKIM if enabled
  1014. if (!empty($this->DKIM_domain)
  1015. && !empty($this->DKIM_private)
  1016. && !empty($this->DKIM_selector)
  1017. && file_exists($this->DKIM_private)) {
  1018. $header_dkim = $this->DKIM_Add(
  1019. $this->MIMEHeader . $this->mailHeader,
  1020. $this->encodeHeader($this->secureHeader($this->Subject)),
  1021. $this->MIMEBody
  1022. );
  1023. $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
  1024. str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
  1025. }
  1026. return true;
  1027. } catch (phpmailerException $exc) {
  1028. $this->setError($exc->getMessage());
  1029. if ($this->exceptions) {
  1030. throw $exc;
  1031. }
  1032. return false;
  1033. }
  1034. }
  1035. /**
  1036. * Actually send a message.
  1037. * Send the email via the selected mechanism
  1038. * @throws phpmailerException
  1039. * @return boolean
  1040. */
  1041. public function postSend()
  1042. {
  1043. try {
  1044. // Choose the mailer and send through it
  1045. switch ($this->Mailer) {
  1046. case 'sendmail':
  1047. case 'qmail':
  1048. return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
  1049. case 'smtp':
  1050. return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
  1051. case 'mail':
  1052. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  1053. default:
  1054. $sendMethod = $this->Mailer.'Send';
  1055. if (method_exists($this, $sendMethod)) {
  1056. return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
  1057. }
  1058. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  1059. }
  1060. } catch (phpmailerException $exc) {
  1061. $this->setError($exc->getMessage());
  1062. $this->edebug($exc->getMessage());
  1063. if ($this->exceptions) {
  1064. throw $exc;
  1065. }
  1066. }
  1067. return false;
  1068. }
  1069. /**
  1070. * Send mail using the $Sendmail program.
  1071. * @param string $header The message headers
  1072. * @param string $body The message body
  1073. * @see PHPMailer::$Sendmail
  1074. * @throws phpmailerException
  1075. * @access protected
  1076. * @return boolean
  1077. */
  1078. protected function sendmailSend($header, $body)
  1079. {
  1080. if ($this->Sender != '') {
  1081. if ($this->Mailer == 'qmail') {
  1082. $sendmail = sprintf('%s -f%s', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  1083. } else {
  1084. $sendmail = sprintf('%s -oi -f%s -t', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  1085. }
  1086. } else {
  1087. if ($this->Mailer == 'qmail') {
  1088. $sendmail = sprintf('%s', escapeshellcmd($this->Sendmail));
  1089. } else {
  1090. $sendmail = sprintf('%s -oi -t', escapeshellcmd($this->Sendmail));
  1091. }
  1092. }
  1093. if ($this->SingleTo) {
  1094. foreach ($this->SingleToArray as $toAddr) {
  1095. if (!@$mail = popen($sendmail, 'w')) {
  1096. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1097. }
  1098. fputs($mail, 'To: ' . $toAddr . "\n");
  1099. fputs($mail, $header);
  1100. fputs($mail, $body);
  1101. $result = pclose($mail);
  1102. $this->doCallback(
  1103. ($result == 0),
  1104. array($toAddr),
  1105. $this->cc,
  1106. $this->bcc,
  1107. $this->Subject,
  1108. $body,
  1109. $this->From
  1110. );
  1111. if ($result != 0) {
  1112. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1113. }
  1114. }
  1115. } else {
  1116. if (!@$mail = popen($sendmail, 'w')) {
  1117. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1118. }
  1119. fputs($mail, $header);
  1120. fputs($mail, $body);
  1121. $result = pclose($mail);
  1122. $this->doCallback(($result == 0), $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1123. if ($result != 0) {
  1124. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1125. }
  1126. }
  1127. return true;
  1128. }
  1129. /**
  1130. * Send mail using the PHP mail() function.
  1131. * @param string $header The message headers
  1132. * @param string $body The message body
  1133. * @link http://www.php.net/manual/en/book.mail.php
  1134. * @throws phpmailerException
  1135. * @access protected
  1136. * @return boolean
  1137. */
  1138. protected function mailSend($header, $body)
  1139. {
  1140. $toArr = array();
  1141. foreach ($this->to as $toaddr) {
  1142. $toArr[] = $this->addrFormat($toaddr);
  1143. }
  1144. $to = implode(', ', $toArr);
  1145. if (empty($this->Sender)) {
  1146. $params = ' ';
  1147. } else {
  1148. $params = sprintf('-f%s', $this->Sender);
  1149. }
  1150. if ($this->Sender != '' and !ini_get('safe_mode')) {
  1151. $old_from = ini_get('sendmail_from');
  1152. ini_set('sendmail_from', $this->Sender);
  1153. }
  1154. $result = false;
  1155. if ($this->SingleTo && count($toArr) > 1) {
  1156. foreach ($toArr as $toAddr) {
  1157. $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
  1158. $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1159. }
  1160. } else {
  1161. $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
  1162. $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1163. }
  1164. if (isset($old_from)) {
  1165. ini_set('sendmail_from', $old_from);
  1166. }
  1167. if (!$result) {
  1168. throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
  1169. }
  1170. return true;
  1171. }
  1172. /**
  1173. * Get an instance to use for SMTP operations.
  1174. * Override this function to load your own SMTP implementation
  1175. * @return SMTP
  1176. */
  1177. public function getSMTPInstance()
  1178. {
  1179. if (!is_object($this->smtp)) {
  1180. $this->smtp = new SMTP;
  1181. }
  1182. return $this->smtp;
  1183. }
  1184. /**
  1185. * Send mail via SMTP.
  1186. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  1187. * Uses the PHPMailerSMTP class by default.
  1188. * @see PHPMailer::getSMTPInstance() to use a different class.
  1189. * @param string $header The message headers
  1190. * @param string $body The message body
  1191. * @throws phpmailerException
  1192. * @uses SMTP
  1193. * @access protected
  1194. * @return boolean
  1195. */
  1196. protected function smtpSend($header, $body)
  1197. {
  1198. $bad_rcpt = array();
  1199. if (!$this->smtpConnect($this->SMTPOptions)) {
  1200. throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
  1201. }
  1202. if ('' == $this->Sender) {
  1203. $smtp_from = $this->From;
  1204. } else {
  1205. $smtp_from = $this->Sender;
  1206. }
  1207. if (!$this->smtp->mail($smtp_from)) {
  1208. $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
  1209. throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
  1210. }
  1211. // Attempt to send to all recipients
  1212. foreach (array($this->to, $this->cc, $this->bcc) as $togroup) {
  1213. foreach ($togroup as $to) {
  1214. if (!$this->smtp->recipient($to[0])) {
  1215. $error = $this->smtp->getError();
  1216. $bad_rcpt[] = array('to' => $to[0], 'error' => $error['detail']);
  1217. $isSent = false;
  1218. } else {
  1219. $isSent = true;
  1220. }
  1221. $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From);
  1222. }
  1223. }
  1224. // Only send the DATA command if we have viable recipients
  1225. if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
  1226. throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
  1227. }
  1228. if ($this->SMTPKeepAlive) {
  1229. $this->smtp->reset();
  1230. } else {
  1231. $this->smtp->quit();
  1232. $this->smtp->close();
  1233. }
  1234. //Create error message for any bad addresses
  1235. if (count($bad_rcpt) > 0) {
  1236. $errstr = '';
  1237. foreach ($bad_rcpt as $bad) {
  1238. $errstr .= $bad['to'] . ': ' . $bad['error'];
  1239. }
  1240. throw new phpmailerException(
  1241. $this->lang('recipients_failed') . $errstr,
  1242. self::STOP_CONTINUE
  1243. );
  1244. }
  1245. return true;
  1246. }
  1247. /**
  1248. * Initiate a connection to an SMTP server.
  1249. * Returns false if the operation failed.
  1250. * @param array $options An array of options compatible with stream_context_create()
  1251. * @uses SMTP
  1252. * @access public
  1253. * @throws phpmailerException
  1254. * @return boolean
  1255. */
  1256. public function smtpConnect($options = array())
  1257. {
  1258. if (is_null($this->smtp)) {
  1259. $this->smtp = $this->getSMTPInstance();
  1260. }
  1261. // Already connected?
  1262. if ($this->smtp->connected()) {
  1263. return true;
  1264. }
  1265. $this->smtp->setTimeout($this->Timeout);
  1266. $this->smtp->setDebugLevel($this->SMTPDebug);
  1267. $this->smtp->setDebugOutput($this->Debugoutput);
  1268. $this->smtp->setVerp($this->do_verp);
  1269. $hosts = explode(';', $this->Host);
  1270. $lastexception = null;
  1271. foreach ($hosts as $hostentry) {
  1272. $hostinfo = array();
  1273. if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
  1274. // Not a valid host entry
  1275. continue;
  1276. }
  1277. // $hostinfo[2]: optional ssl or tls prefix
  1278. // $hostinfo[3]: the hostname
  1279. // $hostinfo[4]: optional port number
  1280. // The host string prefix can temporarily override the current setting for SMTPSecure
  1281. // If it's not specified, the default value is used
  1282. $prefix = '';
  1283. $secure = $this->SMTPSecure;
  1284. $tls = ($this->SMTPSecure == 'tls');
  1285. if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
  1286. $prefix = 'ssl://';
  1287. $tls = false; // Can't have SSL and TLS at the same time
  1288. $secure = 'ssl';
  1289. } elseif ($hostinfo[2] == 'tls') {
  1290. $tls = true;
  1291. // tls doesn't use a prefix
  1292. $secure = 'tls';
  1293. }
  1294. //Do we need the OpenSSL extension?
  1295. $sslext = defined('OPENSSL_ALGO_SHA1');
  1296. if ('tls' === $secure or 'ssl' === $secure) {
  1297. //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
  1298. if (!$sslext) {
  1299. throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL);
  1300. }
  1301. }
  1302. $host = $hostinfo[3];
  1303. $port = $this->Port;
  1304. $tport = (integer)$hostinfo[4];
  1305. if ($tport > 0 and $tport < 65536) {
  1306. $port = $tport;
  1307. }
  1308. if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
  1309. try {
  1310. if ($this->Helo) {
  1311. $hello = $this->Helo;
  1312. } else {
  1313. $hello = $this->serverHostname();
  1314. }
  1315. $this->smtp->hello($hello);
  1316. //Automatically enable TLS encryption if:
  1317. // * it's not disabled
  1318. // * we have openssl extension
  1319. // * we are not already using SSL
  1320. // * the server offers STARTTLS
  1321. if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) {
  1322. $tls = true;
  1323. }
  1324. if ($tls) {
  1325. if (!$this->smtp->startTLS()) {
  1326. throw new phpmailerException($this->lang('connect_host'));
  1327. }
  1328. // We must resend HELO after tls negotiation
  1329. $this->smtp->hello($hello);
  1330. }
  1331. if ($this->SMTPAuth) {
  1332. if (!$this->smtp->authenticate(
  1333. $this->Username,
  1334. $this->Password,
  1335. $this->AuthType,
  1336. $this->Realm,
  1337. $this->Workstation
  1338. )
  1339. ) {
  1340. throw new phpmailerException($this->lang('authenticate'));
  1341. }
  1342. }
  1343. return true;
  1344. } catch (phpmailerException $exc) {
  1345. $lastexception = $exc;
  1346. $this->edebug($exc->getMessage());
  1347. // We must have connected, but then failed TLS or Auth, so close connection nicely
  1348. $this->smtp->quit();
  1349. }
  1350. }
  1351. }
  1352. // If we get here, all connection attempts have failed, so close connection hard
  1353. $this->smtp->close();
  1354. // As we've caught all exceptions, just report whatever the last one was
  1355. if ($this->exceptions and !is_null($lastexception)) {
  1356. throw $lastexception;
  1357. }
  1358. return false;
  1359. }
  1360. /**
  1361. * Close the active SMTP session if one exists.
  1362. * @return void
  1363. */
  1364. public function smtpClose()
  1365. {
  1366. if ($this->smtp !== null) {
  1367. if ($this->smtp->connected()) {
  1368. $this->smtp->quit();
  1369. $this->smtp->close();
  1370. }
  1371. }
  1372. }
  1373. /**
  1374. * Set the language for error messages.
  1375. * Returns false if it cannot load the language file.
  1376. * The default language is English.
  1377. * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
  1378. * @param string $lang_path Path to the language file directory, with trailing separator (slash)
  1379. * @return boolean
  1380. * @access public
  1381. */
  1382. public function se

Large files files are truncated, but you can click here to view the full file