PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/core/model/modx/mail/phpmailer/class.phpmailer.php

http://github.com/modxcms/revolution
PHP | 4064 lines | 2388 code | 252 blank | 1424 comment | 387 complexity | 0c8aa4025e77285efb963d911764a3e0 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, BSD-3-Clause, 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. * @var string
  32. */
  33. public $Version = '5.2.28';
  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. * @var integer
  39. */
  40. public $Priority = null;
  41. /**
  42. * The character set of the message.
  43. * @var string
  44. */
  45. public $CharSet = 'iso-8859-1';
  46. /**
  47. * The MIME Content-type of the message.
  48. * @var string
  49. */
  50. public $ContentType = 'text/plain';
  51. /**
  52. * The message encoding.
  53. * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
  54. * @var string
  55. */
  56. public $Encoding = '8bit';
  57. /**
  58. * Holds the most recent mailer error message.
  59. * @var string
  60. */
  61. public $ErrorInfo = '';
  62. /**
  63. * The From email address for the message.
  64. * @var string
  65. */
  66. public $From = 'root@localhost';
  67. /**
  68. * The From name of the message.
  69. * @var 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. * @var 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. * @var 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. * @var string
  90. */
  91. public $Subject = '';
  92. /**
  93. * An HTML or plain text message body.
  94. * If HTML then call isHTML(true).
  95. * @var 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. * @var 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. * @var string
  113. */
  114. public $Ical = '';
  115. /**
  116. * The complete compiled MIME message body.
  117. * @access protected
  118. * @var string
  119. */
  120. protected $MIMEBody = '';
  121. /**
  122. * The complete compiled MIME message headers.
  123. * @var string
  124. * @access protected
  125. */
  126. protected $MIMEHeader = '';
  127. /**
  128. * Extra headers that createHeader() doesn't fold in.
  129. * @var 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. * @var integer
  137. */
  138. public $WordWrap = 0;
  139. /**
  140. * Which method to use to send mail.
  141. * Options: "mail", "sendmail", or "smtp".
  142. * @var string
  143. */
  144. public $Mailer = 'mail';
  145. /**
  146. * The path to the sendmail program.
  147. * @var 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. * @var 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. * @var 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, also known as read receipt.
  165. * @var string
  166. */
  167. public $ConfirmReadingTo = '';
  168. /**
  169. * The hostname to use in the Message-ID header and as default HELO string.
  170. * If empty, PHPMailer attempts to find one with, in order,
  171. * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value
  172. * 'localhost.localdomain'.
  173. * @var 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. * You can set your own, but it must be in the format "<id@domain>",
  180. * as defined in RFC5322 section 3.6.4 or it will be ignored.
  181. * @see https://tools.ietf.org/html/rfc5322#section-3.6.4
  182. * @var string
  183. */
  184. public $MessageID = '';
  185. /**
  186. * The message Date to be used in the Date header.
  187. * If empty, the current date will be added.
  188. * @var string
  189. */
  190. public $MessageDate = '';
  191. /**
  192. * SMTP hosts.
  193. * Either a single hostname or multiple semicolon-delimited hostnames.
  194. * You can also specify a different port
  195. * for each host by using this format: [hostname:port]
  196. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  197. * You can also specify encryption type, for example:
  198. * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
  199. * Hosts will be tried in order.
  200. * @var string
  201. */
  202. public $Host = 'localhost';
  203. /**
  204. * The default SMTP server port.
  205. * @var integer
  206. * @TODO Why is this needed when the SMTP class takes care of it?
  207. */
  208. public $Port = 25;
  209. /**
  210. * The SMTP HELO of the message.
  211. * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find
  212. * one with the same method described above for $Hostname.
  213. * @var string
  214. * @see PHPMailer::$Hostname
  215. */
  216. public $Helo = '';
  217. /**
  218. * What kind of encryption to use on the SMTP connection.
  219. * Options: '', 'ssl' or 'tls'
  220. * @var string
  221. */
  222. public $SMTPSecure = '';
  223. /**
  224. * Whether to enable TLS encryption automatically if a server supports it,
  225. * even if `SMTPSecure` is not set to 'tls'.
  226. * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
  227. * @var boolean
  228. */
  229. public $SMTPAutoTLS = true;
  230. /**
  231. * Whether to use SMTP authentication.
  232. * Uses the Username and Password properties.
  233. * @var boolean
  234. * @see PHPMailer::$Username
  235. * @see PHPMailer::$Password
  236. */
  237. public $SMTPAuth = false;
  238. /**
  239. * Options array passed to stream_context_create when connecting via SMTP.
  240. * @var array
  241. */
  242. public $SMTPOptions = array();
  243. /**
  244. * SMTP username.
  245. * @var string
  246. */
  247. public $Username = '';
  248. /**
  249. * SMTP password.
  250. * @var string
  251. */
  252. public $Password = '';
  253. /**
  254. * SMTP auth type.
  255. * Options are CRAM-MD5, LOGIN, PLAIN, NTLM, XOAUTH2, attempted in that order if not specified
  256. * @var string
  257. */
  258. public $AuthType = '';
  259. /**
  260. * SMTP realm.
  261. * Used for NTLM auth
  262. * @var string
  263. */
  264. public $Realm = '';
  265. /**
  266. * SMTP workstation.
  267. * Used for NTLM auth
  268. * @var string
  269. */
  270. public $Workstation = '';
  271. /**
  272. * The SMTP server timeout in seconds.
  273. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
  274. * @var integer
  275. */
  276. public $Timeout = 300;
  277. /**
  278. * SMTP class debug output mode.
  279. * Debug output level.
  280. * Options:
  281. * * `0` No output
  282. * * `1` Commands
  283. * * `2` Data and commands
  284. * * `3` As 2 plus connection status
  285. * * `4` Low-level data output
  286. * @var integer
  287. * @see SMTP::$do_debug
  288. */
  289. public $SMTPDebug = 0;
  290. /**
  291. * How to handle debug output.
  292. * Options:
  293. * * `echo` Output plain-text as-is, appropriate for CLI
  294. * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
  295. * * `error_log` Output to error log as configured in php.ini
  296. *
  297. * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
  298. * <code>
  299. * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
  300. * </code>
  301. * @var string|callable
  302. * @see SMTP::$Debugoutput
  303. */
  304. public $Debugoutput = 'echo';
  305. /**
  306. * Whether to keep SMTP connection open after each message.
  307. * If this is set to true then to close the connection
  308. * requires an explicit call to smtpClose().
  309. * @var boolean
  310. */
  311. public $SMTPKeepAlive = false;
  312. /**
  313. * Whether to split multiple to addresses into multiple messages
  314. * or send them all in one message.
  315. * Only supported in `mail` and `sendmail` transports, not in SMTP.
  316. * @var boolean
  317. */
  318. public $SingleTo = false;
  319. /**
  320. * Storage for addresses when SingleTo is enabled.
  321. * @var array
  322. * @TODO This should really not be public
  323. */
  324. public $SingleToArray = array();
  325. /**
  326. * Whether to generate VERP addresses on send.
  327. * Only applicable when sending via SMTP.
  328. * @link https://en.wikipedia.org/wiki/Variable_envelope_return_path
  329. * @link http://www.postfix.org/VERP_README.html Postfix VERP info
  330. * @var boolean
  331. */
  332. public $do_verp = false;
  333. /**
  334. * Whether to allow sending messages with an empty body.
  335. * @var boolean
  336. */
  337. public $AllowEmpty = false;
  338. /**
  339. * The default line ending.
  340. * @note The default remains "\n". We force CRLF where we know
  341. * it must be used via self::CRLF.
  342. * @var string
  343. */
  344. public $LE = "\n";
  345. /**
  346. * DKIM selector.
  347. * @var string
  348. */
  349. public $DKIM_selector = '';
  350. /**
  351. * DKIM Identity.
  352. * Usually the email address used as the source of the email.
  353. * @var string
  354. */
  355. public $DKIM_identity = '';
  356. /**
  357. * DKIM passphrase.
  358. * Used if your key is encrypted.
  359. * @var string
  360. */
  361. public $DKIM_passphrase = '';
  362. /**
  363. * DKIM signing domain name.
  364. * @example 'example.com'
  365. * @var string
  366. */
  367. public $DKIM_domain = '';
  368. /**
  369. * DKIM private key file path.
  370. * @var string
  371. */
  372. public $DKIM_private = '';
  373. /**
  374. * DKIM private key string.
  375. * If set, takes precedence over `$DKIM_private`.
  376. * @var string
  377. */
  378. public $DKIM_private_string = '';
  379. /**
  380. * Callback Action function name.
  381. *
  382. * The function that handles the result of the send email action.
  383. * It is called out by send() for each email sent.
  384. *
  385. * Value can be any php callable: http://www.php.net/is_callable
  386. *
  387. * Parameters:
  388. * boolean $result result of the send action
  389. * array $to email addresses of the recipients
  390. * array $cc cc email addresses
  391. * array $bcc bcc email addresses
  392. * string $subject the subject
  393. * string $body the email body
  394. * string $from email address of sender
  395. * @var string
  396. */
  397. public $action_function = '';
  398. /**
  399. * What to put in the X-Mailer header.
  400. * Options: An empty string for PHPMailer default, whitespace for none, or a string to use
  401. * @var string
  402. */
  403. public $XMailer = '';
  404. /**
  405. * Which validator to use by default when validating email addresses.
  406. * May be a callable to inject your own validator, but there are several built-in validators.
  407. * @see PHPMailer::validateAddress()
  408. * @var string|callable
  409. * @static
  410. */
  411. public static $validator = 'auto';
  412. /**
  413. * An instance of the SMTP sender class.
  414. * @var SMTP
  415. * @access protected
  416. */
  417. protected $smtp = null;
  418. /**
  419. * The array of 'to' names and addresses.
  420. * @var array
  421. * @access protected
  422. */
  423. protected $to = array();
  424. /**
  425. * The array of 'cc' names and addresses.
  426. * @var array
  427. * @access protected
  428. */
  429. protected $cc = array();
  430. /**
  431. * The array of 'bcc' names and addresses.
  432. * @var array
  433. * @access protected
  434. */
  435. protected $bcc = array();
  436. /**
  437. * The array of reply-to names and addresses.
  438. * @var array
  439. * @access protected
  440. */
  441. protected $ReplyTo = array();
  442. /**
  443. * An array of all kinds of addresses.
  444. * Includes all of $to, $cc, $bcc
  445. * @var array
  446. * @access protected
  447. * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc
  448. */
  449. protected $all_recipients = array();
  450. /**
  451. * An array of names and addresses queued for validation.
  452. * In send(), valid and non duplicate entries are moved to $all_recipients
  453. * and one of $to, $cc, or $bcc.
  454. * This array is used only for addresses with IDN.
  455. * @var array
  456. * @access protected
  457. * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc
  458. * @see PHPMailer::$all_recipients
  459. */
  460. protected $RecipientsQueue = array();
  461. /**
  462. * An array of reply-to names and addresses queued for validation.
  463. * In send(), valid and non duplicate entries are moved to $ReplyTo.
  464. * This array is used only for addresses with IDN.
  465. * @var array
  466. * @access protected
  467. * @see PHPMailer::$ReplyTo
  468. */
  469. protected $ReplyToQueue = array();
  470. /**
  471. * The array of attachments.
  472. * @var array
  473. * @access protected
  474. */
  475. protected $attachment = array();
  476. /**
  477. * The array of custom headers.
  478. * @var array
  479. * @access protected
  480. */
  481. protected $CustomHeader = array();
  482. /**
  483. * The most recent Message-ID (including angular brackets).
  484. * @var string
  485. * @access protected
  486. */
  487. protected $lastMessageID = '';
  488. /**
  489. * The message's MIME type.
  490. * @var string
  491. * @access protected
  492. */
  493. protected $message_type = '';
  494. /**
  495. * The array of MIME boundary strings.
  496. * @var array
  497. * @access protected
  498. */
  499. protected $boundary = array();
  500. /**
  501. * The array of available languages.
  502. * @var array
  503. * @access protected
  504. */
  505. protected $language = array();
  506. /**
  507. * The number of errors encountered.
  508. * @var integer
  509. * @access protected
  510. */
  511. protected $error_count = 0;
  512. /**
  513. * The S/MIME certificate file path.
  514. * @var string
  515. * @access protected
  516. */
  517. protected $sign_cert_file = '';
  518. /**
  519. * The S/MIME key file path.
  520. * @var string
  521. * @access protected
  522. */
  523. protected $sign_key_file = '';
  524. /**
  525. * The optional S/MIME extra certificates ("CA Chain") file path.
  526. * @var string
  527. * @access protected
  528. */
  529. protected $sign_extracerts_file = '';
  530. /**
  531. * The S/MIME password for the key.
  532. * Used only if the key is encrypted.
  533. * @var string
  534. * @access protected
  535. */
  536. protected $sign_key_pass = '';
  537. /**
  538. * Whether to throw exceptions for errors.
  539. * @var boolean
  540. * @access protected
  541. */
  542. protected $exceptions = false;
  543. /**
  544. * Unique ID used for message ID and boundaries.
  545. * @var string
  546. * @access protected
  547. */
  548. protected $uniqueid = '';
  549. /**
  550. * Error severity: message only, continue processing.
  551. */
  552. const STOP_MESSAGE = 0;
  553. /**
  554. * Error severity: message, likely ok to continue processing.
  555. */
  556. const STOP_CONTINUE = 1;
  557. /**
  558. * Error severity: message, plus full stop, critical error reached.
  559. */
  560. const STOP_CRITICAL = 2;
  561. /**
  562. * SMTP RFC standard line ending.
  563. */
  564. const CRLF = "\r\n";
  565. /**
  566. * The maximum line length allowed by RFC 2822 section 2.1.1
  567. * @var integer
  568. */
  569. const MAX_LINE_LENGTH = 998;
  570. /**
  571. * Constructor.
  572. * @param boolean $exceptions Should we throw external exceptions?
  573. */
  574. public function __construct($exceptions = null)
  575. {
  576. if ($exceptions !== null) {
  577. $this->exceptions = (boolean)$exceptions;
  578. }
  579. //Pick an appropriate debug output format automatically
  580. $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html');
  581. }
  582. /**
  583. * Destructor.
  584. */
  585. public function __destruct()
  586. {
  587. //Close any open SMTP connection nicely
  588. $this->smtpClose();
  589. }
  590. /**
  591. * Call mail() in a safe_mode-aware fashion.
  592. * Also, unless sendmail_path points to sendmail (or something that
  593. * claims to be sendmail), don't pass params (not a perfect fix,
  594. * but it will do)
  595. * @param string $to To
  596. * @param string $subject Subject
  597. * @param string $body Message Body
  598. * @param string $header Additional Header(s)
  599. * @param string $params Params
  600. * @access private
  601. * @return boolean
  602. */
  603. private function mailPassthru($to, $subject, $body, $header, $params)
  604. {
  605. //Check overloading of mail function to avoid double-encoding
  606. if (ini_get('mbstring.func_overload') & 1) {
  607. $subject = $this->secureHeader($subject);
  608. } else {
  609. $subject = $this->encodeHeader($this->secureHeader($subject));
  610. }
  611. //Can't use additional_parameters in safe_mode, calling mail() with null params breaks
  612. //@link http://php.net/manual/en/function.mail.php
  613. if (ini_get('safe_mode') or !$this->UseSendmailOptions or is_null($params)) {
  614. $result = @mail($to, $subject, $body, $header);
  615. } else {
  616. $result = @mail($to, $subject, $body, $header, $params);
  617. }
  618. return $result;
  619. }
  620. /**
  621. * Output debugging info via user-defined method.
  622. * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
  623. * @see PHPMailer::$Debugoutput
  624. * @see PHPMailer::$SMTPDebug
  625. * @param string $str
  626. */
  627. protected function edebug($str)
  628. {
  629. if ($this->SMTPDebug <= 0) {
  630. return;
  631. }
  632. //Avoid clash with built-in function names
  633. if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
  634. call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
  635. return;
  636. }
  637. switch ($this->Debugoutput) {
  638. case 'error_log':
  639. //Don't output, just log
  640. error_log($str);
  641. break;
  642. case 'html':
  643. //Cleans up output a bit for a better looking, HTML-safe output
  644. echo htmlentities(
  645. preg_replace('/[\r\n]+/', '', $str),
  646. ENT_QUOTES,
  647. 'UTF-8'
  648. )
  649. . "<br>\n";
  650. break;
  651. case 'echo':
  652. default:
  653. //Normalize line breaks
  654. $str = preg_replace('/\r\n?/ms', "\n", $str);
  655. echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
  656. "\n",
  657. "\n \t ",
  658. trim($str)
  659. ) . "\n";
  660. }
  661. }
  662. /**
  663. * Sets message type to HTML or plain.
  664. * @param boolean $isHtml True for HTML mode.
  665. * @return void
  666. */
  667. public function isHTML($isHtml = true)
  668. {
  669. if ($isHtml) {
  670. $this->ContentType = 'text/html';
  671. } else {
  672. $this->ContentType = 'text/plain';
  673. }
  674. }
  675. /**
  676. * Send messages using SMTP.
  677. * @return void
  678. */
  679. public function isSMTP()
  680. {
  681. $this->Mailer = 'smtp';
  682. }
  683. /**
  684. * Send messages using PHP's mail() function.
  685. * @return void
  686. */
  687. public function isMail()
  688. {
  689. $this->Mailer = 'mail';
  690. }
  691. /**
  692. * Send messages using $Sendmail.
  693. * @return void
  694. */
  695. public function isSendmail()
  696. {
  697. $ini_sendmail_path = ini_get('sendmail_path');
  698. if (!stristr($ini_sendmail_path, 'sendmail')) {
  699. $this->Sendmail = '/usr/sbin/sendmail';
  700. } else {
  701. $this->Sendmail = $ini_sendmail_path;
  702. }
  703. $this->Mailer = 'sendmail';
  704. }
  705. /**
  706. * Send messages using qmail.
  707. * @return void
  708. */
  709. public function isQmail()
  710. {
  711. $ini_sendmail_path = ini_get('sendmail_path');
  712. if (!stristr($ini_sendmail_path, 'qmail')) {
  713. $this->Sendmail = '/var/qmail/bin/qmail-inject';
  714. } else {
  715. $this->Sendmail = $ini_sendmail_path;
  716. }
  717. $this->Mailer = 'qmail';
  718. }
  719. /**
  720. * Add a "To" address.
  721. * @param string $address The email address to send to
  722. * @param string $name
  723. * @return boolean true on success, false if address already used or invalid in some way
  724. */
  725. public function addAddress($address, $name = '')
  726. {
  727. return $this->addOrEnqueueAnAddress('to', $address, $name);
  728. }
  729. /**
  730. * Add a "CC" address.
  731. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
  732. * @param string $address The email address to send to
  733. * @param string $name
  734. * @return boolean true on success, false if address already used or invalid in some way
  735. */
  736. public function addCC($address, $name = '')
  737. {
  738. return $this->addOrEnqueueAnAddress('cc', $address, $name);
  739. }
  740. /**
  741. * Add a "BCC" address.
  742. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
  743. * @param string $address The email address to send to
  744. * @param string $name
  745. * @return boolean true on success, false if address already used or invalid in some way
  746. */
  747. public function addBCC($address, $name = '')
  748. {
  749. return $this->addOrEnqueueAnAddress('bcc', $address, $name);
  750. }
  751. /**
  752. * Add a "Reply-To" address.
  753. * @param string $address The email address to reply to
  754. * @param string $name
  755. * @return boolean true on success, false if address already used or invalid in some way
  756. */
  757. public function addReplyTo($address, $name = '')
  758. {
  759. return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
  760. }
  761. /**
  762. * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer
  763. * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still
  764. * be modified after calling this function), addition of such addresses is delayed until send().
  765. * Addresses that have been added already return false, but do not throw exceptions.
  766. * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
  767. * @param string $address The email address to send, resp. to reply to
  768. * @param string $name
  769. * @throws phpmailerException
  770. * @return boolean true on success, false if address already used or invalid in some way
  771. * @access protected
  772. */
  773. protected function addOrEnqueueAnAddress($kind, $address, $name)
  774. {
  775. $address = trim($address);
  776. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  777. if (($pos = strrpos($address, '@')) === false) {
  778. // At-sign is misssing.
  779. $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address";
  780. $this->setError($error_message);
  781. $this->edebug($error_message);
  782. if ($this->exceptions) {
  783. throw new phpmailerException($error_message);
  784. }
  785. return false;
  786. }
  787. $params = array($kind, $address, $name);
  788. // Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
  789. if ($this->has8bitChars(substr($address, ++$pos)) and $this->idnSupported()) {
  790. if ($kind != 'Reply-To') {
  791. if (!array_key_exists($address, $this->RecipientsQueue)) {
  792. $this->RecipientsQueue[$address] = $params;
  793. return true;
  794. }
  795. } else {
  796. if (!array_key_exists($address, $this->ReplyToQueue)) {
  797. $this->ReplyToQueue[$address] = $params;
  798. return true;
  799. }
  800. }
  801. return false;
  802. }
  803. // Immediately add standard addresses without IDN.
  804. return call_user_func_array(array($this, 'addAnAddress'), $params);
  805. }
  806. /**
  807. * Add an address to one of the recipient arrays or to the ReplyTo array.
  808. * Addresses that have been added already return false, but do not throw exceptions.
  809. * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
  810. * @param string $address The email address to send, resp. to reply to
  811. * @param string $name
  812. * @throws phpmailerException
  813. * @return boolean true on success, false if address already used or invalid in some way
  814. * @access protected
  815. */
  816. protected function addAnAddress($kind, $address, $name = '')
  817. {
  818. if (!in_array($kind, array('to', 'cc', 'bcc', 'Reply-To'))) {
  819. $error_message = $this->lang('Invalid recipient kind: ') . $kind;
  820. $this->setError($error_message);
  821. $this->edebug($error_message);
  822. if ($this->exceptions) {
  823. throw new phpmailerException($error_message);
  824. }
  825. return false;
  826. }
  827. if (!$this->validateAddress($address)) {
  828. $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address";
  829. $this->setError($error_message);
  830. $this->edebug($error_message);
  831. if ($this->exceptions) {
  832. throw new phpmailerException($error_message);
  833. }
  834. return false;
  835. }
  836. if ($kind != 'Reply-To') {
  837. if (!array_key_exists(strtolower($address), $this->all_recipients)) {
  838. array_push($this->$kind, array($address, $name));
  839. $this->all_recipients[strtolower($address)] = true;
  840. return true;
  841. }
  842. } else {
  843. if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  844. $this->ReplyTo[strtolower($address)] = array($address, $name);
  845. return true;
  846. }
  847. }
  848. return false;
  849. }
  850. /**
  851. * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
  852. * of the form "display name <address>" into an array of name/address pairs.
  853. * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
  854. * Note that quotes in the name part are removed.
  855. * @param string $addrstr The address list string
  856. * @param bool $useimap Whether to use the IMAP extension to parse the list
  857. * @return array
  858. * @link http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
  859. */
  860. public function parseAddresses($addrstr, $useimap = true)
  861. {
  862. $addresses = array();
  863. if ($useimap and function_exists('imap_rfc822_parse_adrlist')) {
  864. //Use this built-in parser if it's available
  865. $list = imap_rfc822_parse_adrlist($addrstr, '');
  866. foreach ($list as $address) {
  867. if ($address->host != '.SYNTAX-ERROR.') {
  868. if ($this->validateAddress($address->mailbox . '@' . $address->host)) {
  869. $addresses[] = array(
  870. 'name' => (property_exists($address, 'personal') ? $address->personal : ''),
  871. 'address' => $address->mailbox . '@' . $address->host
  872. );
  873. }
  874. }
  875. }
  876. } else {
  877. //Use this simpler parser
  878. $list = explode(',', $addrstr);
  879. foreach ($list as $address) {
  880. $address = trim($address);
  881. //Is there a separate name part?
  882. if (strpos($address, '<') === false) {
  883. //No separate name, just use the whole thing
  884. if ($this->validateAddress($address)) {
  885. $addresses[] = array(
  886. 'name' => '',
  887. 'address' => $address
  888. );
  889. }
  890. } else {
  891. list($name, $email) = explode('<', $address);
  892. $email = trim(str_replace('>', '', $email));
  893. if ($this->validateAddress($email)) {
  894. $addresses[] = array(
  895. 'name' => trim(str_replace(array('"', "'"), '', $name)),
  896. 'address' => $email
  897. );
  898. }
  899. }
  900. }
  901. }
  902. return $addresses;
  903. }
  904. /**
  905. * Set the From and FromName properties.
  906. * @param string $address
  907. * @param string $name
  908. * @param boolean $auto Whether to also set the Sender address, defaults to true
  909. * @throws phpmailerException
  910. * @return boolean
  911. */
  912. public function setFrom($address, $name = '', $auto = true)
  913. {
  914. $address = trim($address);
  915. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  916. // Don't validate now addresses with IDN. Will be done in send().
  917. if (($pos = strrpos($address, '@')) === false or
  918. (!$this->has8bitChars(substr($address, ++$pos)) or !$this->idnSupported()) and
  919. !$this->validateAddress($address)) {
  920. $error_message = $this->lang('invalid_address') . " (setFrom) $address";
  921. $this->setError($error_message);
  922. $this->edebug($error_message);
  923. if ($this->exceptions) {
  924. throw new phpmailerException($error_message);
  925. }
  926. return false;
  927. }
  928. $this->From = $address;
  929. $this->FromName = $name;
  930. if ($auto) {
  931. if (empty($this->Sender)) {
  932. $this->Sender = $address;
  933. }
  934. }
  935. return true;
  936. }
  937. /**
  938. * Return the Message-ID header of the last email.
  939. * Technically this is the value from the last time the headers were created,
  940. * but it's also the message ID of the last sent message except in
  941. * pathological cases.
  942. * @return string
  943. */
  944. public function getLastMessageID()
  945. {
  946. return $this->lastMessageID;
  947. }
  948. /**
  949. * Check that a string looks like an email address.
  950. * @param string $address The email address to check
  951. * @param string|callable $patternselect A selector for the validation pattern to use :
  952. * * `auto` Pick best pattern automatically;
  953. * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
  954. * * `pcre` Use old PCRE implementation;
  955. * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
  956. * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
  957. * * `noregex` Don't use a regex: super fast, really dumb.
  958. * Alternatively you may pass in a callable to inject your own validator, for example:
  959. * PHPMailer::validateAddress('user@example.com', function($address) {
  960. * return (strpos($address, '@') !== false);
  961. * });
  962. * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.
  963. * @return boolean
  964. * @static
  965. * @access public
  966. */
  967. public static function validateAddress($address, $patternselect = null)
  968. {
  969. if (is_null($patternselect)) {
  970. $patternselect = self::$validator;
  971. }
  972. if (is_callable($patternselect)) {
  973. return call_user_func($patternselect, $address);
  974. }
  975. //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
  976. if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) {
  977. return false;
  978. }
  979. if (!$patternselect or $patternselect == 'auto') {
  980. //Check this constant first so it works when extension_loaded() is disabled by safe mode
  981. //Constant was added in PHP 5.2.4
  982. if (defined('PCRE_VERSION')) {
  983. //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2
  984. if (version_compare(PCRE_VERSION, '8.0.3') >= 0) {
  985. $patternselect = 'pcre8';
  986. } else {
  987. $patternselect = 'pcre';
  988. }
  989. } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) {
  990. //Fall back to older PCRE
  991. $patternselect = 'pcre';
  992. } else {
  993. //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
  994. if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
  995. $patternselect = 'php';
  996. } else {
  997. $patternselect = 'noregex';
  998. }
  999. }
  1000. }
  1001. switch ($patternselect) {
  1002. case 'pcre8':
  1003. /**
  1004. * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains.
  1005. * @link http://squiloople.com/2009/12/20/email-address-validation/
  1006. * @copyright 2009-2010 Michael Rushton
  1007. * Feel free to use and redistribute this code. But please keep this copyright notice.
  1008. */
  1009. return (boolean)preg_match(
  1010. '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
  1011. '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
  1012. '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
  1013. '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
  1014. '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
  1015. '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
  1016. '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
  1017. '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  1018. '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
  1019. $address
  1020. );
  1021. case 'pcre':
  1022. //An older regex that doesn't need a recent PCRE
  1023. return (boolean)preg_match(
  1024. '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
  1025. '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
  1026. '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
  1027. '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
  1028. '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
  1029. '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
  1030. '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
  1031. '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
  1032. '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  1033. '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
  1034. $address
  1035. );
  1036. case 'html5':
  1037. /**
  1038. * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
  1039. * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
  1040. */
  1041. return (boolean)preg_match(
  1042. '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
  1043. '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
  1044. $address
  1045. );
  1046. case 'noregex':
  1047. //No PCRE! Do something _very_ approximate!
  1048. //Check the address is 3 chars or longer and contains an @ that's not the first or last char
  1049. return (strlen($address) >= 3
  1050. and strpos($address, '@') >= 1
  1051. and strpos($address, '@') != strlen($address) - 1);
  1052. case 'php':
  1053. default:
  1054. return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
  1055. }
  1056. }
  1057. /**
  1058. * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the
  1059. * "intl" and "mbstring" PHP extensions.
  1060. * @return bool "true" if required functions for IDN support are present
  1061. */
  1062. public function idnSupported()
  1063. {
  1064. // @TODO: Write our own "idn_to_ascii" function for PHP <= 5.2.
  1065. return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding');
  1066. }
  1067. /**
  1068. * Converts IDN in given email address to its ASCII form, also known as punycode, if possible.
  1069. * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.
  1070. * This function silently returns unmodified address if:
  1071. * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
  1072. * - Conversion to punycode is impossible (e.g. required PHP functions are not available)
  1073. * or fails for any reason (e.g. domain has characters not allowed in an IDN)
  1074. * @see PHPMailer::$CharSet
  1075. * @param string $address The email address to convert
  1076. * @return string The encoded address in ASCII form
  1077. */
  1078. public function punyencodeAddress($address)
  1079. {
  1080. // Verify we have required functions, CharSet, and at-sign.
  1081. if ($this->idnSupported() and
  1082. !empty($this->CharSet) and
  1083. ($pos = strrpos($address, '@')) !== false) {
  1084. $domain = substr($address, ++$pos);
  1085. // Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
  1086. if ($this->has8bitChars($domain) and @mb_check_encoding($domain, $this->CharSet)) {
  1087. $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet);
  1088. if (($punycode = defined('INTL_IDNA_VARIANT_UTS46') ?
  1089. idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46) :
  1090. idn_to_ascii($domain)) !== false) {
  1091. return substr($address, 0, $pos) . $punycode;
  1092. }
  1093. }
  1094. }
  1095. return $address;
  1096. }
  1097. /**
  1098. * Create a message and send it.
  1099. * Uses the sending method specified by $Mailer.
  1100. * @throws phpmailerException
  1101. * @return boolean false on error - See the ErrorInfo property for details of the error.
  1102. */
  1103. public function send()
  1104. {
  1105. try {
  1106. if (!$this->preSend()) {
  1107. return false;
  1108. }
  1109. return $this->postSend();
  1110. } catch (phpmailerException $exc) {
  1111. $this->mailHeader = '';
  1112. $this->setError($exc->getMessage());
  1113. if ($this->exceptions) {
  1114. throw $exc;
  1115. }
  1116. return false;
  1117. }
  1118. }
  1119. /**
  1120. * Prepare a message for sending.
  1121. * @throws phpmailerException
  1122. * @return boolean
  1123. */
  1124. public function preSend()
  1125. {
  1126. try {
  1127. $this->error_count = 0; // Reset errors
  1128. $this->mailHeader = '';
  1129. // Dequeue recipient and Reply-To addresses with IDN
  1130. foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
  1131. $params[1] = $this->punyencodeAddress($params[1]);
  1132. call_user_func_array(array($this, 'addAnAddress'), $params);
  1133. }
  1134. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  1135. throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
  1136. }
  1137. // Validate From, Sender, and ConfirmReadingTo addresses
  1138. foreach (array('From', 'Sender', 'ConfirmReadingTo') as $address_kind) {
  1139. $this->$address_kind = trim($this->$address_kind);
  1140. if (empty($this->$address_kind)) {
  1141. continue;
  1142. }
  1143. $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
  1144. if (!$this->validateAddress($this->$address_kind)) {
  1145. $error_message = $this->lang('invalid_address') . ' (punyEncode) ' . $this->$address_kind;
  1146. $this->setError($error_message);
  1147. $this->edebug($error_message);
  1148. if ($this->exceptions) {
  1149. throw new phpmailerException($error_message);
  1150. }
  1151. return false;
  1152. }
  1153. }
  1154. // Set whether the message is multipart/alternative
  1155. if ($this->alternativeExists()) {
  1156. $this->ContentType = 'multipart/alternative';
  1157. }
  1158. $this->setMessageType();
  1159. // Refuse to send an empty message unless we are specifically allowing it
  1160. if (!$this->AllowEmpty and empty($this->Body)) {
  1161. throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
  1162. }
  1163. // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
  1164. $this->MIMEHeader = '';
  1165. $this->MIMEBody = $this->createBody();
  1166. // createBody may have added some headers, so retain them
  1167. $tempheaders = $this->MIMEHeader;
  1168. $this->MIMEHeader = $this->createHeader();
  1169. $this->MIMEHeader .= $tempheaders;
  1170. // To capture the complete message when using mail(), create
  1171. // an extra header list which createHeader() doesn't fold in
  1172. if ($this->Mailer == 'mail') {
  1173. if (count($this->to) > 0) {
  1174. $this->mailHeader .= $this->addrAppend('To', $this->to);
  1175. } else {
  1176. $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
  1177. }
  1178. $this->mailHeader .= $this->headerLine(
  1179. 'Subject',
  1180. $this->encodeHeader($this->secureHeader(trim($this->Subject)))
  1181. );
  1182. }
  1183. // Sign with DKIM if enabled
  1184. if (!empty($this->DKIM_domain)
  1185. and !empty($this->DKIM_selector)
  1186. and (!empty($this->DKIM_private_string)
  1187. or (!empty($this->DKIM_private)
  1188. and self::isPermittedPath($this->DKIM_private)
  1189. and file_exists($this->DKIM_private)
  1190. )
  1191. )
  1192. ) {
  1193. $header_dkim = $this->DKIM_Add(
  1194. $this->MIMEHeader . $this->mailHeader,
  1195. $this->encodeHeader($this->secureHeader($this->Subject)),
  1196. $this->MIMEBody
  1197. );
  1198. $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
  1199. str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
  1200. }
  1201. return true;
  1202. } catch (phpmailerException $exc) {
  1203. $this->setError($exc->getMessage());
  1204. if ($this->exceptions) {
  1205. throw $exc;
  1206. }
  1207. return false;
  1208. }
  1209. }
  1210. /**
  1211. * Actually send a message.
  1212. * Send the email via the selected mechanism
  1213. * @throws phpmailerException
  1214. * @return boolean
  1215. */
  1216. public function postSend()
  1217. {
  1218. try {
  1219. // Choose the mailer and send through it
  1220. switch ($this->Mailer) {
  1221. case 'sendmail':
  1222. case 'qmail':
  1223. return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
  1224. case 'smtp':
  1225. return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
  1226. case 'mail':
  1227. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  1228. default:
  1229. $sendMethod = $this->Mailer.'Send';
  1230. if (method_exists($this, $sendMethod)) {
  1231. return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
  1232. }
  1233. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  1234. }
  1235. } catch (phpmailerException $exc) {
  1236. $this->setError($exc->getMessage());
  1237. $this->edebug($exc->getMessage());
  1238. if ($this->exceptions) {
  1239. throw $exc;
  1240. }
  1241. }
  1242. return false;
  1243. }
  1244. /**
  1245. * Send mail using the $Sendmail program.
  1246. * @param string $header The message headers
  1247. * @param string $body The message body
  1248. * @see PHPMailer::$Sendmail
  1249. * @throws phpmailerException
  1250. * @access protected
  1251. * @return boolean
  1252. */
  1253. protected function sendmailSend($header, $body)
  1254. {
  1255. // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
  1256. if (!empty($this->Sender) and self::isShellSafe($this->Sender)) {
  1257. if ($this->Mailer == 'qmail') {
  1258. $sendmailFmt = '%s -f%s';
  1259. } else {
  1260. $sendmailFmt = '%s -oi -f%s -t';
  1261. }
  1262. } else {
  1263. if ($this->Mailer == 'qmail') {
  1264. $sendmailFmt = '%s';
  1265. } else {
  1266. $sendmailFmt = '%s -oi -t';
  1267. }
  1268. }
  1269. // TODO: If possible, this should be changed to escapeshellarg. Needs thorough testing.
  1270. $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);
  1271. if ($this->SingleTo) {
  1272. foreach ($this->SingleToArray as $toAddr) {
  1273. if (!@$mail = popen($sendmail, 'w')) {
  1274. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1275. }
  1276. fputs($mail, 'To: ' . $toAddr . "\n");
  1277. fputs($mail, $header);
  1278. fputs($mail, $body);
  1279. $result = pclose($mail);
  1280. $this->doCallback(
  1281. ($result == 0),
  1282. array($toAddr),
  1283. $this->cc,
  1284. $this->bcc,
  1285. $this->Subject,
  1286. $body,
  1287. $this->From
  1288. );
  1289. if ($result != 0) {
  1290. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1291. }
  1292. }
  1293. } else {
  1294. if (!@$mail = popen($sendmail, 'w')) {
  1295. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1296. }
  1297. fputs($mail, $header);
  1298. fputs($mail, $body);
  1299. $result = pclose($mail);
  1300. $this->doCallback(
  1301. ($result == 0),
  1302. $this->to,
  1303. $this->cc,
  1304. $this->bcc,
  1305. $this->Subject,
  1306. $body,
  1307. $this->From
  1308. );
  1309. if ($result != 0) {
  1310. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1311. }
  1312. }
  1313. return true;
  1314. }
  1315. /**
  1316. * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.
  1317. *
  1318. * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.
  1319. * @param string $string The string to be validated
  1320. * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report
  1321. * @access protected
  1322. * @return boolean
  1323. */
  1324. protected static function isShellSafe($string)
  1325. {
  1326. // Future-proof
  1327. if (escapeshellcmd($string) !== $string
  1328. or !in_array(escapeshellarg($string), array("'$string'", "\"$string\""))
  1329. ) {
  1330. return false;
  1331. }
  1332. $length = strlen($string);
  1333. for ($i = 0; $i < $length; $i++) {
  1334. $c = $string[$i];
  1335. // All other characters have a special meaning in at least one common shell, including = and +.
  1336. // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
  1337. // Note that this does permit non-Latin alphanumeric character…

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