Guest User

php mailer

a guest
Dec 12th, 2017
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 148.28 KB | None | 0 0
  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. /**
  21. * PHPMailer - PHP email creation and transport class.
  22. * @package PHPMailer
  23. * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  24. * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  25. * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  26. * @author Brent R. Matzelle (original founder)
  27. */
  28. class PHPMailer
  29. {
  30. /**
  31. * The PHPMailer Version number.
  32. * @var string
  33. */
  34. public $Version = '5.2.23';
  35.  
  36. /**
  37. * Email priority.
  38. * Options: null (default), 1 = High, 3 = Normal, 5 = low.
  39. * When null, the header is not set at all.
  40. * @var integer
  41. */
  42. public $Priority = null;
  43.  
  44. /**
  45. * The character set of the message.
  46. * @var string
  47. */
  48. public $CharSet = 'iso-8859-1';
  49.  
  50. /**
  51. * The MIME Content-type of the message.
  52. * @var string
  53. */
  54. public $ContentType = 'text/plain';
  55.  
  56. /**
  57. * The message encoding.
  58. * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
  59. * @var string
  60. */
  61. public $Encoding = '8bit';
  62.  
  63. /**
  64. * Holds the most recent mailer error message.
  65. * @var string
  66. */
  67. public $ErrorInfo = '';
  68.  
  69. /**
  70. * The From email address for the message.
  71. * @var string
  72. */
  73. public $From = 'root@localhost';
  74.  
  75. /**
  76. * The From name of the message.
  77. * @var string
  78. */
  79. public $FromName = 'Root User';
  80.  
  81. /**
  82. * The Sender email (Return-Path) of the message.
  83. * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  84. * @var string
  85. */
  86. public $Sender = '';
  87.  
  88. /**
  89. * The Return-Path of the message.
  90. * If empty, it will be set to either From or Sender.
  91. * @var string
  92. * @deprecated Email senders should never set a return-path header;
  93. * it's the receiver's job (RFC5321 section 4.4), so this no longer does anything.
  94. * @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference
  95. */
  96. public $ReturnPath = '';
  97.  
  98. /**
  99. * The Subject of the message.
  100. * @var string
  101. */
  102. public $Subject = '';
  103.  
  104. /**
  105. * An HTML or plain text message body.
  106. * If HTML then call isHTML(true).
  107. * @var string
  108. */
  109. public $Body = '';
  110.  
  111. /**
  112. * The plain-text message body.
  113. * This body can be read by mail clients that do not have HTML email
  114. * capability such as mutt & Eudora.
  115. * Clients that can read HTML will view the normal Body.
  116. * @var string
  117. */
  118. public $AltBody = '';
  119.  
  120. /**
  121. * An iCal message part body.
  122. * Only supported in simple alt or alt_inline message types
  123. * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator
  124. * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
  125. * @link http://kigkonsult.se/iCalcreator/
  126. * @var string
  127. */
  128. public $Ical = '';
  129.  
  130. /**
  131. * The complete compiled MIME message body.
  132. * @access protected
  133. * @var string
  134. */
  135. protected $MIMEBody = '';
  136.  
  137. /**
  138. * The complete compiled MIME message headers.
  139. * @var string
  140. * @access protected
  141. */
  142. protected $MIMEHeader = '';
  143.  
  144. /**
  145. * Extra headers that createHeader() doesn't fold in.
  146. * @var string
  147. * @access protected
  148. */
  149. protected $mailHeader = '';
  150.  
  151. /**
  152. * Word-wrap the message body to this number of chars.
  153. * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
  154. * @var integer
  155. */
  156. public $WordWrap = 0;
  157.  
  158. /**
  159. * Which method to use to send mail.
  160. * Options: "mail", "sendmail", or "smtp".
  161. * @var string
  162. */
  163. public $Mailer = 'mail';
  164.  
  165. /**
  166. * The path to the sendmail program.
  167. * @var string
  168. */
  169. public $Sendmail = '/usr/sbin/sendmail';
  170.  
  171. /**
  172. * Whether mail() uses a fully sendmail-compatible MTA.
  173. * One which supports sendmail's "-oi -f" options.
  174. * @var boolean
  175. */
  176. public $UseSendmailOptions = true;
  177.  
  178. /**
  179. * Path to PHPMailer plugins.
  180. * Useful if the SMTP class is not in the PHP include path.
  181. * @var string
  182. * @deprecated Should not be needed now there is an autoloader.
  183. */
  184. public $PluginDir = '';
  185.  
  186. /**
  187. * The email address that a reading confirmation should be sent to, also known as read receipt.
  188. * @var string
  189. */
  190. public $ConfirmReadingTo = '';
  191.  
  192. /**
  193. * The hostname to use in the Message-ID header and as default HELO string.
  194. * If empty, PHPMailer attempts to find one with, in order,
  195. * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value
  196. * 'localhost.localdomain'.
  197. * @var string
  198. */
  199. public $Hostname = '';
  200.  
  201. /**
  202. * An ID to be used in the Message-ID header.
  203. * If empty, a unique id will be generated.
  204. * You can set your own, but it must be in the format "<id@domain>",
  205. * as defined in RFC5322 section 3.6.4 or it will be ignored.
  206. * @see https://tools.ietf.org/html/rfc5322#section-3.6.4
  207. * @var string
  208. */
  209. public $MessageID = '';
  210.  
  211. /**
  212. * The message Date to be used in the Date header.
  213. * If empty, the current date will be added.
  214. * @var string
  215. */
  216. public $MessageDate = '';
  217.  
  218. /**
  219. * SMTP hosts.
  220. * Either a single hostname or multiple semicolon-delimited hostnames.
  221. * You can also specify a different port
  222. * for each host by using this format: [hostname:port]
  223. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  224. * You can also specify encryption type, for example:
  225. * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
  226. * Hosts will be tried in order.
  227. * @var string
  228. */
  229. public $Host = 'localhost';
  230.  
  231. /**
  232. * The default SMTP server port.
  233. * @var integer
  234. * @TODO Why is this needed when the SMTP class takes care of it?
  235. */
  236. public $Port = 25;
  237.  
  238. /**
  239. * The SMTP HELO of the message.
  240. * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find
  241. * one with the same method described above for $Hostname.
  242. * @var string
  243. * @see PHPMailer::$Hostname
  244. */
  245. public $Helo = '';
  246.  
  247. /**
  248. * What kind of encryption to use on the SMTP connection.
  249. * Options: '', 'ssl' or 'tls'
  250. * @var string
  251. */
  252. public $SMTPSecure = '';
  253.  
  254. /**
  255. * Whether to enable TLS encryption automatically if a server supports it,
  256. * even if `SMTPSecure` is not set to 'tls'.
  257. * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
  258. * @var boolean
  259. */
  260. public $SMTPAutoTLS = true;
  261.  
  262. /**
  263. * Whether to use SMTP authentication.
  264. * Uses the Username and Password properties.
  265. * @var boolean
  266. * @see PHPMailer::$Username
  267. * @see PHPMailer::$Password
  268. */
  269. public $SMTPAuth = false;
  270.  
  271. /**
  272. * Options array passed to stream_context_create when connecting via SMTP.
  273. * @var array
  274. */
  275. public $SMTPOptions = array();
  276.  
  277. /**
  278. * SMTP username.
  279. * @var string
  280. */
  281. public $Username = '';
  282.  
  283. /**
  284. * SMTP password.
  285. * @var string
  286. */
  287. public $Password = '';
  288.  
  289. /**
  290. * SMTP auth type.
  291. * Options are CRAM-MD5, LOGIN, PLAIN, NTLM, XOAUTH2, attempted in that order if not specified
  292. * @var string
  293. */
  294. public $AuthType = '';
  295.  
  296. /**
  297. * SMTP realm.
  298. * Used for NTLM auth
  299. * @var string
  300. */
  301. public $Realm = '';
  302.  
  303. /**
  304. * SMTP workstation.
  305. * Used for NTLM auth
  306. * @var string
  307. */
  308. public $Workstation = '';
  309.  
  310. /**
  311. * The SMTP server timeout in seconds.
  312. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
  313. * @var integer
  314. */
  315. public $Timeout = 300;
  316.  
  317. /**
  318. * SMTP class debug output mode.
  319. * Debug output level.
  320. * Options:
  321. * * `0` No output
  322. * * `1` Commands
  323. * * `2` Data and commands
  324. * * `3` As 2 plus connection status
  325. * * `4` Low-level data output
  326. * @var integer
  327. * @see SMTP::$do_debug
  328. */
  329. public $SMTPDebug = 0;
  330.  
  331. /**
  332. * How to handle debug output.
  333. * Options:
  334. * * `echo` Output plain-text as-is, appropriate for CLI
  335. * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
  336. * * `error_log` Output to error log as configured in php.ini
  337. *
  338. * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
  339. * <code>
  340. * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
  341. * </code>
  342. * @var string|callable
  343. * @see SMTP::$Debugoutput
  344. */
  345. public $Debugoutput = 'echo';
  346.  
  347. /**
  348. * Whether to keep SMTP connection open after each message.
  349. * If this is set to true then to close the connection
  350. * requires an explicit call to smtpClose().
  351. * @var boolean
  352. */
  353. public $SMTPKeepAlive = false;
  354.  
  355. /**
  356. * Whether to split multiple to addresses into multiple messages
  357. * or send them all in one message.
  358. * Only supported in `mail` and `sendmail` transports, not in SMTP.
  359. * @var boolean
  360. */
  361. public $SingleTo = false;
  362.  
  363. /**
  364. * Storage for addresses when SingleTo is enabled.
  365. * @var array
  366. * @TODO This should really not be public
  367. */
  368. public $SingleToArray = array();
  369.  
  370. /**
  371. * Whether to generate VERP addresses on send.
  372. * Only applicable when sending via SMTP.
  373. * @link https://en.wikipedia.org/wiki/Variable_envelope_return_path
  374. * @link http://www.postfix.org/VERP_README.html Postfix VERP info
  375. * @var boolean
  376. */
  377. public $do_verp = false;
  378.  
  379. /**
  380. * Whether to allow sending messages with an empty body.
  381. * @var boolean
  382. */
  383. public $AllowEmpty = false;
  384.  
  385. /**
  386. * The default line ending.
  387. * @note The default remains "\n". We force CRLF where we know
  388. * it must be used via self::CRLF.
  389. * @var string
  390. */
  391. public $LE = "\n";
  392.  
  393. /**
  394. * DKIM selector.
  395. * @var string
  396. */
  397. public $DKIM_selector = '';
  398.  
  399. /**
  400. * DKIM Identity.
  401. * Usually the email address used as the source of the email.
  402. * @var string
  403. */
  404. public $DKIM_identity = '';
  405.  
  406. /**
  407. * DKIM passphrase.
  408. * Used if your key is encrypted.
  409. * @var string
  410. */
  411. public $DKIM_passphrase = '';
  412.  
  413. /**
  414. * DKIM signing domain name.
  415. * @example 'example.com'
  416. * @var string
  417. */
  418. public $DKIM_domain = '';
  419.  
  420. /**
  421. * DKIM private key file path.
  422. * @var string
  423. */
  424. public $DKIM_private = '';
  425.  
  426. /**
  427. * DKIM private key string.
  428. * If set, takes precedence over `$DKIM_private`.
  429. * @var string
  430. */
  431. public $DKIM_private_string = '';
  432.  
  433. /**
  434. * Callback Action function name.
  435. *
  436. * The function that handles the result of the send email action.
  437. * It is called out by send() for each email sent.
  438. *
  439. * Value can be any php callable: http://www.php.net/is_callable
  440. *
  441. * Parameters:
  442. * boolean $result result of the send action
  443. * string $to email address of the recipient
  444. * string $cc cc email addresses
  445. * string $bcc bcc email addresses
  446. * string $subject the subject
  447. * string $body the email body
  448. * string $from email address of sender
  449. * @var string
  450. */
  451. public $action_function = '';
  452.  
  453. /**
  454. * What to put in the X-Mailer header.
  455. * Options: An empty string for PHPMailer default, whitespace for none, or a string to use
  456. * @var string
  457. */
  458. public $XMailer = '';
  459.  
  460. /**
  461. * Which validator to use by default when validating email addresses.
  462. * May be a callable to inject your own validator, but there are several built-in validators.
  463. * @see PHPMailer::validateAddress()
  464. * @var string|callable
  465. * @static
  466. */
  467. public static $validator = 'auto';
  468.  
  469. /**
  470. * An instance of the SMTP sender class.
  471. * @var SMTP
  472. * @access protected
  473. */
  474. protected $smtp = null;
  475.  
  476. /**
  477. * The array of 'to' names and addresses.
  478. * @var array
  479. * @access protected
  480. */
  481. protected $to = array();
  482.  
  483. /**
  484. * The array of 'cc' names and addresses.
  485. * @var array
  486. * @access protected
  487. */
  488. protected $cc = array();
  489.  
  490. /**
  491. * The array of 'bcc' names and addresses.
  492. * @var array
  493. * @access protected
  494. */
  495. protected $bcc = array();
  496.  
  497. /**
  498. * The array of reply-to names and addresses.
  499. * @var array
  500. * @access protected
  501. */
  502. protected $ReplyTo = array();
  503.  
  504. /**
  505. * An array of all kinds of addresses.
  506. * Includes all of $to, $cc, $bcc
  507. * @var array
  508. * @access protected
  509. * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc
  510. */
  511. protected $all_recipients = array();
  512.  
  513. /**
  514. * An array of names and addresses queued for validation.
  515. * In send(), valid and non duplicate entries are moved to $all_recipients
  516. * and one of $to, $cc, or $bcc.
  517. * This array is used only for addresses with IDN.
  518. * @var array
  519. * @access protected
  520. * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc
  521. * @see PHPMailer::$all_recipients
  522. */
  523. protected $RecipientsQueue = array();
  524.  
  525. /**
  526. * An array of reply-to names and addresses queued for validation.
  527. * In send(), valid and non duplicate entries are moved to $ReplyTo.
  528. * This array is used only for addresses with IDN.
  529. * @var array
  530. * @access protected
  531. * @see PHPMailer::$ReplyTo
  532. */
  533. protected $ReplyToQueue = array();
  534.  
  535. /**
  536. * The array of attachments.
  537. * @var array
  538. * @access protected
  539. */
  540. protected $attachment = array();
  541.  
  542. /**
  543. * The array of custom headers.
  544. * @var array
  545. * @access protected
  546. */
  547. protected $CustomHeader = array();
  548.  
  549. /**
  550. * The most recent Message-ID (including angular brackets).
  551. * @var string
  552. * @access protected
  553. */
  554. protected $lastMessageID = '';
  555.  
  556. /**
  557. * The message's MIME type.
  558. * @var string
  559. * @access protected
  560. */
  561. protected $message_type = '';
  562.  
  563. /**
  564. * The array of MIME boundary strings.
  565. * @var array
  566. * @access protected
  567. */
  568. protected $boundary = array();
  569.  
  570. /**
  571. * The array of available languages.
  572. * @var array
  573. * @access protected
  574. */
  575. protected $language = array();
  576.  
  577. /**
  578. * The number of errors encountered.
  579. * @var integer
  580. * @access protected
  581. */
  582. protected $error_count = 0;
  583.  
  584. /**
  585. * The S/MIME certificate file path.
  586. * @var string
  587. * @access protected
  588. */
  589. protected $sign_cert_file = '';
  590.  
  591. /**
  592. * The S/MIME key file path.
  593. * @var string
  594. * @access protected
  595. */
  596. protected $sign_key_file = '';
  597.  
  598. /**
  599. * The optional S/MIME extra certificates ("CA Chain") file path.
  600. * @var string
  601. * @access protected
  602. */
  603. protected $sign_extracerts_file = '';
  604.  
  605. /**
  606. * The S/MIME password for the key.
  607. * Used only if the key is encrypted.
  608. * @var string
  609. * @access protected
  610. */
  611. protected $sign_key_pass = '';
  612.  
  613. /**
  614. * Whether to throw exceptions for errors.
  615. * @var boolean
  616. * @access protected
  617. */
  618. protected $exceptions = false;
  619.  
  620. /**
  621. * Unique ID used for message ID and boundaries.
  622. * @var string
  623. * @access protected
  624. */
  625. protected $uniqueid = '';
  626.  
  627. /**
  628. * Error severity: message only, continue processing.
  629. */
  630. const STOP_MESSAGE = 0;
  631.  
  632. /**
  633. * Error severity: message, likely ok to continue processing.
  634. */
  635. const STOP_CONTINUE = 1;
  636.  
  637. /**
  638. * Error severity: message, plus full stop, critical error reached.
  639. */
  640. const STOP_CRITICAL = 2;
  641.  
  642. /**
  643. * SMTP RFC standard line ending.
  644. */
  645. const CRLF = "\r\n";
  646.  
  647. /**
  648. * The maximum line length allowed by RFC 2822 section 2.1.1
  649. * @var integer
  650. */
  651. const MAX_LINE_LENGTH = 998;
  652.  
  653. /**
  654. * Constructor.
  655. * @param boolean $exceptions Should we throw external exceptions?
  656. */
  657. public function __construct($exceptions = null)
  658. {
  659. if ($exceptions !== null) {
  660. $this->exceptions = (boolean)$exceptions;
  661. }
  662. }
  663.  
  664. /**
  665. * Destructor.
  666. */
  667. public function __destruct()
  668. {
  669. //Close any open SMTP connection nicely
  670. $this->smtpClose();
  671. }
  672.  
  673. /**
  674. * Call mail() in a safe_mode-aware fashion.
  675. * Also, unless sendmail_path points to sendmail (or something that
  676. * claims to be sendmail), don't pass params (not a perfect fix,
  677. * but it will do)
  678. * @param string $to To
  679. * @param string $subject Subject
  680. * @param string $body Message Body
  681. * @param string $header Additional Header(s)
  682. * @param string $params Params
  683. * @access private
  684. * @return boolean
  685. */
  686. private function mailPassthru($to, $subject, $body, $header, $params)
  687. {
  688. //Check overloading of mail function to avoid double-encoding
  689. if (ini_get('mbstring.func_overload') & 1) {
  690. $subject = $this->secureHeader($subject);
  691. } else {
  692. $subject = $this->encodeHeader($this->secureHeader($subject));
  693. }
  694.  
  695. //Can't use additional_parameters in safe_mode, calling mail() with null params breaks
  696. //@link http://php.net/manual/en/function.mail.php
  697. if (ini_get('safe_mode') or !$this->UseSendmailOptions or is_null($params)) {
  698. $result = @mail($to, $subject, $body, $header);
  699. } else {
  700. $result = @mail($to, $subject, $body, $header, $params);
  701. }
  702. return $result;
  703. }
  704. /**
  705. * Output debugging info via user-defined method.
  706. * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
  707. * @see PHPMailer::$Debugoutput
  708. * @see PHPMailer::$SMTPDebug
  709. * @param string $str
  710. */
  711. protected function edebug($str)
  712. {
  713. if ($this->SMTPDebug <= 0) {
  714. return;
  715. }
  716. //Avoid clash with built-in function names
  717. if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
  718. call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
  719. return;
  720. }
  721. switch ($this->Debugoutput) {
  722. case 'error_log':
  723. //Don't output, just log
  724. error_log($str);
  725. break;
  726. case 'html':
  727. //Cleans up output a bit for a better looking, HTML-safe output
  728. echo htmlentities(
  729. preg_replace('/[\r\n]+/', '', $str),
  730. ENT_QUOTES,
  731. 'UTF-8'
  732. )
  733. . "<br>\n";
  734. break;
  735. case 'echo':
  736. default:
  737. //Normalize line breaks
  738. $str = preg_replace('/\r\n?/ms', "\n", $str);
  739. echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
  740. "\n",
  741. "\n \t ",
  742. trim($str)
  743. ) . "\n";
  744. }
  745. }
  746.  
  747. /**
  748. * Sets message type to HTML or plain.
  749. * @param boolean $isHtml True for HTML mode.
  750. * @return void
  751. */
  752. public function isHTML($isHtml = true)
  753. {
  754. if ($isHtml) {
  755. $this->ContentType = 'text/html';
  756. } else {
  757. $this->ContentType = 'text/plain';
  758. }
  759. }
  760.  
  761. /**
  762. * Send messages using SMTP.
  763. * @return void
  764. */
  765. public function isSMTP()
  766. {
  767. $this->Mailer = 'smtp';
  768. }
  769.  
  770. /**
  771. * Send messages using PHP's mail() function.
  772. * @return void
  773. */
  774. public function isMail()
  775. {
  776. $this->Mailer = 'mail';
  777. }
  778.  
  779. /**
  780. * Send messages using $Sendmail.
  781. * @return void
  782. */
  783. public function isSendmail()
  784. {
  785. $ini_sendmail_path = ini_get('sendmail_path');
  786.  
  787. if (!stristr($ini_sendmail_path, 'sendmail')) {
  788. $this->Sendmail = '/usr/sbin/sendmail';
  789. } else {
  790. $this->Sendmail = $ini_sendmail_path;
  791. }
  792. $this->Mailer = 'sendmail';
  793. }
  794.  
  795. /**
  796. * Send messages using qmail.
  797. * @return void
  798. */
  799. public function isQmail()
  800. {
  801. $ini_sendmail_path = ini_get('sendmail_path');
  802.  
  803. if (!stristr($ini_sendmail_path, 'qmail')) {
  804. $this->Sendmail = '/var/qmail/bin/qmail-inject';
  805. } else {
  806. $this->Sendmail = $ini_sendmail_path;
  807. }
  808. $this->Mailer = 'qmail';
  809. }
  810.  
  811. /**
  812. * Add a "To" address.
  813. * @param string $address The email address to send to
  814. * @param string $name
  815. * @return boolean true on success, false if address already used or invalid in some way
  816. */
  817. public function addAddress($address, $name = '')
  818. {
  819. return $this->addOrEnqueueAnAddress('to', $address, $name);
  820. }
  821.  
  822. /**
  823. * Add a "CC" address.
  824. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
  825. * @param string $address The email address to send to
  826. * @param string $name
  827. * @return boolean true on success, false if address already used or invalid in some way
  828. */
  829. public function addCC($address, $name = '')
  830. {
  831. return $this->addOrEnqueueAnAddress('cc', $address, $name);
  832. }
  833.  
  834. /**
  835. * Add a "BCC" address.
  836. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
  837. * @param string $address The email address to send to
  838. * @param string $name
  839. * @return boolean true on success, false if address already used or invalid in some way
  840. */
  841. public function addBCC($address, $name = '')
  842. {
  843. return $this->addOrEnqueueAnAddress('bcc', $address, $name);
  844. }
  845.  
  846. /**
  847. * Add a "Reply-To" address.
  848. * @param string $address The email address to reply to
  849. * @param string $name
  850. * @return boolean true on success, false if address already used or invalid in some way
  851. */
  852. public function addReplyTo($address, $name = '')
  853. {
  854. return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
  855. }
  856.  
  857. /**
  858. * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer
  859. * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still
  860. * be modified after calling this function), addition of such addresses is delayed until send().
  861. * Addresses that have been added already return false, but do not throw exceptions.
  862. * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
  863. * @param string $address The email address to send, resp. to reply to
  864. * @param string $name
  865. * @throws phpmailerException
  866. * @return boolean true on success, false if address already used or invalid in some way
  867. * @access protected
  868. */
  869. protected function addOrEnqueueAnAddress($kind, $address, $name)
  870. {
  871. $address = trim($address);
  872. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  873. if (($pos = strrpos($address, '@')) === false) {
  874. // At-sign is misssing.
  875. $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address";
  876. $this->setError($error_message);
  877. $this->edebug($error_message);
  878. if ($this->exceptions) {
  879. throw new phpmailerException($error_message);
  880. }
  881. return false;
  882. }
  883. $params = array($kind, $address, $name);
  884. // Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
  885. if ($this->has8bitChars(substr($address, ++$pos)) and $this->idnSupported()) {
  886. if ($kind != 'Reply-To') {
  887. if (!array_key_exists($address, $this->RecipientsQueue)) {
  888. $this->RecipientsQueue[$address] = $params;
  889. return true;
  890. }
  891. } else {
  892. if (!array_key_exists($address, $this->ReplyToQueue)) {
  893. $this->ReplyToQueue[$address] = $params;
  894. return true;
  895. }
  896. }
  897. return false;
  898. }
  899. // Immediately add standard addresses without IDN.
  900. return call_user_func_array(array($this, 'addAnAddress'), $params);
  901. }
  902.  
  903. /**
  904. * Add an address to one of the recipient arrays or to the ReplyTo array.
  905. * Addresses that have been added already return false, but do not throw exceptions.
  906. * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
  907. * @param string $address The email address to send, resp. to reply to
  908. * @param string $name
  909. * @throws phpmailerException
  910. * @return boolean true on success, false if address already used or invalid in some way
  911. * @access protected
  912. */
  913. protected function addAnAddress($kind, $address, $name = '')
  914. {
  915. if (!in_array($kind, array('to', 'cc', 'bcc', 'Reply-To'))) {
  916. $error_message = $this->lang('Invalid recipient kind: ') . $kind;
  917. $this->setError($error_message);
  918. $this->edebug($error_message);
  919. if ($this->exceptions) {
  920. throw new phpmailerException($error_message);
  921. }
  922. return false;
  923. }
  924. if (!$this->validateAddress($address)) {
  925. $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address";
  926. $this->setError($error_message);
  927. $this->edebug($error_message);
  928. if ($this->exceptions) {
  929. throw new phpmailerException($error_message);
  930. }
  931. return false;
  932. }
  933. if ($kind != 'Reply-To') {
  934. if (!array_key_exists(strtolower($address), $this->all_recipients)) {
  935. array_push($this->$kind, array($address, $name));
  936. $this->all_recipients[strtolower($address)] = true;
  937. return true;
  938. }
  939. } else {
  940. if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  941. $this->ReplyTo[strtolower($address)] = array($address, $name);
  942. return true;
  943. }
  944. }
  945. return false;
  946. }
  947.  
  948. /**
  949. * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
  950. * of the form "display name <address>" into an array of name/address pairs.
  951. * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
  952. * Note that quotes in the name part are removed.
  953. * @param string $addrstr The address list string
  954. * @param bool $useimap Whether to use the IMAP extension to parse the list
  955. * @return array
  956. * @link http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
  957. */
  958. public function parseAddresses($addrstr, $useimap = true)
  959. {
  960. $addresses = array();
  961. if ($useimap and function_exists('imap_rfc822_parse_adrlist')) {
  962. //Use this built-in parser if it's available
  963. $list = imap_rfc822_parse_adrlist($addrstr, '');
  964. foreach ($list as $address) {
  965. if ($address->host != '.SYNTAX-ERROR.') {
  966. if ($this->validateAddress($address->mailbox . '@' . $address->host)) {
  967. $addresses[] = array(
  968. 'name' => (property_exists($address, 'personal') ? $address->personal : ''),
  969. 'address' => $address->mailbox . '@' . $address->host
  970. );
  971. }
  972. }
  973. }
  974. } else {
  975. //Use this simpler parser
  976. $list = explode(',', $addrstr);
  977. foreach ($list as $address) {
  978. $address = trim($address);
  979. //Is there a separate name part?
  980. if (strpos($address, '<') === false) {
  981. //No separate name, just use the whole thing
  982. if ($this->validateAddress($address)) {
  983. $addresses[] = array(
  984. 'name' => '',
  985. 'address' => $address
  986. );
  987. }
  988. } else {
  989. list($name, $email) = explode('<', $address);
  990. $email = trim(str_replace('>', '', $email));
  991. if ($this->validateAddress($email)) {
  992. $addresses[] = array(
  993. 'name' => trim(str_replace(array('"', "'"), '', $name)),
  994. 'address' => $email
  995. );
  996. }
  997. }
  998. }
  999. }
  1000. return $addresses;
  1001. }
  1002.  
  1003. /**
  1004. * Set the From and FromName properties.
  1005. * @param string $address
  1006. * @param string $name
  1007. * @param boolean $auto Whether to also set the Sender address, defaults to true
  1008. * @throws phpmailerException
  1009. * @return boolean
  1010. */
  1011. public function setFrom($address, $name = '', $auto = true)
  1012. {
  1013. $address = trim($address);
  1014. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  1015. // Don't validate now addresses with IDN. Will be done in send().
  1016. if (($pos = strrpos($address, '@')) === false or
  1017. (!$this->has8bitChars(substr($address, ++$pos)) or !$this->idnSupported()) and
  1018. !$this->validateAddress($address)) {
  1019. $error_message = $this->lang('invalid_address') . " (setFrom) $address";
  1020. $this->setError($error_message);
  1021. $this->edebug($error_message);
  1022. if ($this->exceptions) {
  1023. throw new phpmailerException($error_message);
  1024. }
  1025. return false;
  1026. }
  1027. $this->From = $address;
  1028. $this->FromName = $name;
  1029. if ($auto) {
  1030. if (empty($this->Sender)) {
  1031. $this->Sender = $address;
  1032. }
  1033. }
  1034. return true;
  1035. }
  1036.  
  1037. /**
  1038. * Return the Message-ID header of the last email.
  1039. * Technically this is the value from the last time the headers were created,
  1040. * but it's also the message ID of the last sent message except in
  1041. * pathological cases.
  1042. * @return string
  1043. */
  1044. public function getLastMessageID()
  1045. {
  1046. return $this->lastMessageID;
  1047. }
  1048.  
  1049. /**
  1050. * Check that a string looks like an email address.
  1051. * @param string $address The email address to check
  1052. * @param string|callable $patternselect A selector for the validation pattern to use :
  1053. * * `auto` Pick best pattern automatically;
  1054. * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
  1055. * * `pcre` Use old PCRE implementation;
  1056. * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
  1057. * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
  1058. * * `noregex` Don't use a regex: super fast, really dumb.
  1059. * Alternatively you may pass in a callable to inject your own validator, for example:
  1060. * PHPMailer::validateAddress('user@example.com', function($address) {
  1061. * return (strpos($address, '@') !== false);
  1062. * });
  1063. * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.
  1064. * @return boolean
  1065. * @static
  1066. * @access public
  1067. */
  1068. public static function validateAddress($address, $patternselect = null)
  1069. {
  1070. if (is_null($patternselect)) {
  1071. $patternselect = self::$validator;
  1072. }
  1073. if (is_callable($patternselect)) {
  1074. return call_user_func($patternselect, $address);
  1075. }
  1076. //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
  1077. if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) {
  1078. return false;
  1079. }
  1080. if (!$patternselect or $patternselect == 'auto') {
  1081. //Check this constant first so it works when extension_loaded() is disabled by safe mode
  1082. //Constant was added in PHP 5.2.4
  1083. if (defined('PCRE_VERSION')) {
  1084. //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2
  1085. if (version_compare(PCRE_VERSION, '8.0.3') >= 0) {
  1086. $patternselect = 'pcre8';
  1087. } else {
  1088. $patternselect = 'pcre';
  1089. }
  1090. } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) {
  1091. //Fall back to older PCRE
  1092. $patternselect = 'pcre';
  1093. } else {
  1094. //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
  1095. if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
  1096. $patternselect = 'php';
  1097. } else {
  1098. $patternselect = 'noregex';
  1099. }
  1100. }
  1101. }
  1102. switch ($patternselect) {
  1103. case 'pcre8':
  1104. /**
  1105. * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains.
  1106. * @link http://squiloople.com/2009/12/20/email-address-validation/
  1107. * @copyright 2009-2010 Michael Rushton
  1108. * Feel free to use and redistribute this code. But please keep this copyright notice.
  1109. */
  1110. return (boolean)preg_match(
  1111. '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
  1112. '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
  1113. '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
  1114. '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
  1115. '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
  1116. '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
  1117. '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
  1118. '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  1119. '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
  1120. $address
  1121. );
  1122. case 'pcre':
  1123. //An older regex that doesn't need a recent PCRE
  1124. return (boolean)preg_match(
  1125. '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
  1126. '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
  1127. '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
  1128. '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
  1129. '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
  1130. '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
  1131. '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
  1132. '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
  1133. '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  1134. '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
  1135. $address
  1136. );
  1137. case 'html5':
  1138. /**
  1139. * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
  1140. * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
  1141. */
  1142. return (boolean)preg_match(
  1143. '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
  1144. '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
  1145. $address
  1146. );
  1147. case 'noregex':
  1148. //No PCRE! Do something _very_ approximate!
  1149. //Check the address is 3 chars or longer and contains an @ that's not the first or last char
  1150. return (strlen($address) >= 3
  1151. and strpos($address, '@') >= 1
  1152. and strpos($address, '@') != strlen($address) - 1);
  1153. case 'php':
  1154. default:
  1155. return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
  1156. }
  1157. }
  1158.  
  1159. /**
  1160. * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the
  1161. * "intl" and "mbstring" PHP extensions.
  1162. * @return bool "true" if required functions for IDN support are present
  1163. */
  1164. public function idnSupported()
  1165. {
  1166. // @TODO: Write our own "idn_to_ascii" function for PHP <= 5.2.
  1167. return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding');
  1168. }
  1169.  
  1170. /**
  1171. * Converts IDN in given email address to its ASCII form, also known as punycode, if possible.
  1172. * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.
  1173. * This function silently returns unmodified address if:
  1174. * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
  1175. * - Conversion to punycode is impossible (e.g. required PHP functions are not available)
  1176. * or fails for any reason (e.g. domain has characters not allowed in an IDN)
  1177. * @see PHPMailer::$CharSet
  1178. * @param string $address The email address to convert
  1179. * @return string The encoded address in ASCII form
  1180. */
  1181. public function punyencodeAddress($address)
  1182. {
  1183. // Verify we have required functions, CharSet, and at-sign.
  1184. if ($this->idnSupported() and
  1185. !empty($this->CharSet) and
  1186. ($pos = strrpos($address, '@')) !== false) {
  1187. $domain = substr($address, ++$pos);
  1188. // Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
  1189. if ($this->has8bitChars($domain) and @mb_check_encoding($domain, $this->CharSet)) {
  1190. $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet);
  1191. if (($punycode = defined('INTL_IDNA_VARIANT_UTS46') ?
  1192. idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46) :
  1193. idn_to_ascii($domain)) !== false) {
  1194. return substr($address, 0, $pos) . $punycode;
  1195. }
  1196. }
  1197. }
  1198. return $address;
  1199. }
  1200.  
  1201. /**
  1202. * Create a message and send it.
  1203. * Uses the sending method specified by $Mailer.
  1204. * @throws phpmailerException
  1205. * @return boolean false on error - See the ErrorInfo property for details of the error.
  1206. */
  1207. public function send()
  1208. {
  1209. try {
  1210. if (!$this->preSend()) {
  1211. return false;
  1212. }
  1213. return $this->postSend();
  1214. } catch (phpmailerException $exc) {
  1215. $this->mailHeader = '';
  1216. $this->setError($exc->getMessage());
  1217. if ($this->exceptions) {
  1218. throw $exc;
  1219. }
  1220. return false;
  1221. }
  1222. }
  1223.  
  1224. /**
  1225. * Prepare a message for sending.
  1226. * @throws phpmailerException
  1227. * @return boolean
  1228. */
  1229. public function preSend()
  1230. {
  1231. try {
  1232. $this->error_count = 0; // Reset errors
  1233. $this->mailHeader = '';
  1234.  
  1235. // Dequeue recipient and Reply-To addresses with IDN
  1236. foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
  1237. $params[1] = $this->punyencodeAddress($params[1]);
  1238. call_user_func_array(array($this, 'addAnAddress'), $params);
  1239. }
  1240. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  1241. throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
  1242. }
  1243.  
  1244. // Validate From, Sender, and ConfirmReadingTo addresses
  1245. foreach (array('From', 'Sender', 'ConfirmReadingTo') as $address_kind) {
  1246. $this->$address_kind = trim($this->$address_kind);
  1247. if (empty($this->$address_kind)) {
  1248. continue;
  1249. }
  1250. $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
  1251. if (!$this->validateAddress($this->$address_kind)) {
  1252. $error_message = $this->lang('invalid_address') . ' (punyEncode) ' . $this->$address_kind;
  1253. $this->setError($error_message);
  1254. $this->edebug($error_message);
  1255. if ($this->exceptions) {
  1256. throw new phpmailerException($error_message);
  1257. }
  1258. return false;
  1259. }
  1260. }
  1261.  
  1262. // Set whether the message is multipart/alternative
  1263. if ($this->alternativeExists()) {
  1264. $this->ContentType = 'multipart/alternative';
  1265. }
  1266.  
  1267. $this->setMessageType();
  1268. // Refuse to send an empty message unless we are specifically allowing it
  1269. if (!$this->AllowEmpty and empty($this->Body)) {
  1270. throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
  1271. }
  1272.  
  1273. // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
  1274. $this->MIMEHeader = '';
  1275. $this->MIMEBody = $this->createBody();
  1276. // createBody may have added some headers, so retain them
  1277. $tempheaders = $this->MIMEHeader;
  1278. $this->MIMEHeader = $this->createHeader();
  1279. $this->MIMEHeader .= $tempheaders;
  1280.  
  1281. // To capture the complete message when using mail(), create
  1282. // an extra header list which createHeader() doesn't fold in
  1283. if ($this->Mailer == 'mail') {
  1284. if (count($this->to) > 0) {
  1285. $this->mailHeader .= $this->addrAppend('To', $this->to);
  1286. } else {
  1287. $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
  1288. }
  1289. $this->mailHeader .= $this->headerLine(
  1290. 'Subject',
  1291. $this->encodeHeader($this->secureHeader(trim($this->Subject)))
  1292. );
  1293. }
  1294.  
  1295. // Sign with DKIM if enabled
  1296. if (!empty($this->DKIM_domain)
  1297. && !empty($this->DKIM_selector)
  1298. && (!empty($this->DKIM_private_string)
  1299. || (!empty($this->DKIM_private) && file_exists($this->DKIM_private))
  1300. )
  1301. ) {
  1302. $header_dkim = $this->DKIM_Add(
  1303. $this->MIMEHeader . $this->mailHeader,
  1304. $this->encodeHeader($this->secureHeader($this->Subject)),
  1305. $this->MIMEBody
  1306. );
  1307. $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
  1308. str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
  1309. }
  1310. return true;
  1311. } catch (phpmailerException $exc) {
  1312. $this->setError($exc->getMessage());
  1313. if ($this->exceptions) {
  1314. throw $exc;
  1315. }
  1316. return false;
  1317. }
  1318. }
  1319.  
  1320. /**
  1321. * Actually send a message.
  1322. * Send the email via the selected mechanism
  1323. * @throws phpmailerException
  1324. * @return boolean
  1325. */
  1326. public function postSend()
  1327. {
  1328. try {
  1329. // Choose the mailer and send through it
  1330. switch ($this->Mailer) {
  1331. case 'sendmail':
  1332. case 'qmail':
  1333. return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
  1334. case 'smtp':
  1335. return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
  1336. case 'mail':
  1337. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  1338. default:
  1339. $sendMethod = $this->Mailer.'Send';
  1340. if (method_exists($this, $sendMethod)) {
  1341. return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
  1342. }
  1343.  
  1344. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  1345. }
  1346. } catch (phpmailerException $exc) {
  1347. $this->setError($exc->getMessage());
  1348. $this->edebug($exc->getMessage());
  1349. if ($this->exceptions) {
  1350. throw $exc;
  1351. }
  1352. }
  1353. return false;
  1354. }
  1355.  
  1356. /**
  1357. * Send mail using the $Sendmail program.
  1358. * @param string $header The message headers
  1359. * @param string $body The message body
  1360. * @see PHPMailer::$Sendmail
  1361. * @throws phpmailerException
  1362. * @access protected
  1363. * @return boolean
  1364. */
  1365. protected function sendmailSend($header, $body)
  1366. {
  1367. // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
  1368. if (!empty($this->Sender) and self::isShellSafe($this->Sender)) {
  1369. if ($this->Mailer == 'qmail') {
  1370. $sendmailFmt = '%s -f%s';
  1371. } else {
  1372. $sendmailFmt = '%s -oi -f%s -t';
  1373. }
  1374. } else {
  1375. if ($this->Mailer == 'qmail') {
  1376. $sendmailFmt = '%s';
  1377. } else {
  1378. $sendmailFmt = '%s -oi -t';
  1379. }
  1380. }
  1381.  
  1382. // TODO: If possible, this should be changed to escapeshellarg. Needs thorough testing.
  1383. $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);
  1384.  
  1385. if ($this->SingleTo) {
  1386. foreach ($this->SingleToArray as $toAddr) {
  1387. if (!@$mail = popen($sendmail, 'w')) {
  1388. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1389. }
  1390. fputs($mail, 'To: ' . $toAddr . "\n");
  1391. fputs($mail, $header);
  1392. fputs($mail, $body);
  1393. $result = pclose($mail);
  1394. $this->doCallback(
  1395. ($result == 0),
  1396. array($toAddr),
  1397. $this->cc,
  1398. $this->bcc,
  1399. $this->Subject,
  1400. $body,
  1401. $this->From
  1402. );
  1403. if ($result != 0) {
  1404. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1405. }
  1406. }
  1407. } else {
  1408. if (!@$mail = popen($sendmail, 'w')) {
  1409. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1410. }
  1411. fputs($mail, $header);
  1412. fputs($mail, $body);
  1413. $result = pclose($mail);
  1414. $this->doCallback(
  1415. ($result == 0),
  1416. $this->to,
  1417. $this->cc,
  1418. $this->bcc,
  1419. $this->Subject,
  1420. $body,
  1421. $this->From
  1422. );
  1423. if ($result != 0) {
  1424. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1425. }
  1426. }
  1427. return true;
  1428. }
  1429.  
  1430. /**
  1431. * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.
  1432. *
  1433. * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.
  1434. * @param string $string The string to be validated
  1435. * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report
  1436. * @access protected
  1437. * @return boolean
  1438. */
  1439. protected static function isShellSafe($string)
  1440. {
  1441. // Future-proof
  1442. if (escapeshellcmd($string) !== $string
  1443. or !in_array(escapeshellarg($string), array("'$string'", "\"$string\""))
  1444. ) {
  1445. return false;
  1446. }
  1447.  
  1448. $length = strlen($string);
  1449.  
  1450. for ($i = 0; $i < $length; $i++) {
  1451. $c = $string[$i];
  1452.  
  1453. // All other characters have a special meaning in at least one common shell, including = and +.
  1454. // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
  1455. // Note that this does permit non-Latin alphanumeric characters based on the current locale.
  1456. if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {
  1457. return false;
  1458. }
  1459. }
  1460.  
  1461. return true;
  1462. }
  1463.  
  1464. /**
  1465. * Send mail using the PHP mail() function.
  1466. * @param string $header The message headers
  1467. * @param string $body The message body
  1468. * @link http://www.php.net/manual/en/book.mail.php
  1469. * @throws phpmailerException
  1470. * @access protected
  1471. * @return boolean
  1472. */
  1473. protected function mailSend($header, $body)
  1474. {
  1475. $toArr = array();
  1476. foreach ($this->to as $toaddr) {
  1477. $toArr[] = $this->addrFormat($toaddr);
  1478. }
  1479. $to = implode(', ', $toArr);
  1480.  
  1481. $params = null;
  1482. //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
  1483. if (!empty($this->Sender) and $this->validateAddress($this->Sender)) {
  1484. // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
  1485. if (self::isShellSafe($this->Sender)) {
  1486. $params = sprintf('-f%s', $this->Sender);
  1487. }
  1488. }
  1489. if (!empty($this->Sender) and !ini_get('safe_mode') and $this->validateAddress($this->Sender)) {
  1490. $old_from = ini_get('sendmail_from');
  1491. ini_set('sendmail_from', $this->Sender);
  1492. }
  1493. $result = false;
  1494. if ($this->SingleTo and count($toArr) > 1) {
  1495. foreach ($toArr as $toAddr) {
  1496. $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
  1497. $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1498. }
  1499. } else {
  1500. $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
  1501. $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1502. }
  1503. if (isset($old_from)) {
  1504. ini_set('sendmail_from', $old_from);
  1505. }
  1506. if (!$result) {
  1507. throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
  1508. }
  1509. return true;
  1510. }
  1511.  
  1512. /**
  1513. * Get an instance to use for SMTP operations.
  1514. * Override this function to load your own SMTP implementation
  1515. * @return SMTP
  1516. */
  1517. public function getSMTPInstance()
  1518. {
  1519. if (!is_object($this->smtp)) {
  1520. $this->smtp = new SMTP;
  1521. }
  1522. return $this->smtp;
  1523. }
  1524.  
  1525. /**
  1526. * Send mail via SMTP.
  1527. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  1528. * Uses the PHPMailerSMTP class by default.
  1529. * @see PHPMailer::getSMTPInstance() to use a different class.
  1530. * @param string $header The message headers
  1531. * @param string $body The message body
  1532. * @throws phpmailerException
  1533. * @uses SMTP
  1534. * @access protected
  1535. * @return boolean
  1536. */
  1537. protected function smtpSend($header, $body)
  1538. {
  1539. $bad_rcpt = array();
  1540. if (!$this->smtpConnect($this->SMTPOptions)) {
  1541. throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
  1542. }
  1543. if (!empty($this->Sender) and $this->validateAddress($this->Sender)) {
  1544. $smtp_from = $this->Sender;
  1545. } else {
  1546. $smtp_from = $this->From;
  1547. }
  1548. if (!$this->smtp->mail($smtp_from)) {
  1549. $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
  1550. throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
  1551. }
  1552.  
  1553. // Attempt to send to all recipients
  1554. foreach (array($this->to, $this->cc, $this->bcc) as $togroup) {
  1555. foreach ($togroup as $to) {
  1556. if (!$this->smtp->recipient($to[0])) {
  1557. $error = $this->smtp->getError();
  1558. $bad_rcpt[] = array('to' => $to[0], 'error' => $error['detail']);
  1559. $isSent = false;
  1560. } else {
  1561. $isSent = true;
  1562. }
  1563. $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From);
  1564. }
  1565. }
  1566.  
  1567. // Only send the DATA command if we have viable recipients
  1568. if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
  1569. throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
  1570. }
  1571. if ($this->SMTPKeepAlive) {
  1572. $this->smtp->reset();
  1573. } else {
  1574. $this->smtp->quit();
  1575. $this->smtp->close();
  1576. }
  1577. //Create error message for any bad addresses
  1578. if (count($bad_rcpt) > 0) {
  1579. $errstr = '';
  1580. foreach ($bad_rcpt as $bad) {
  1581. $errstr .= $bad['to'] . ': ' . $bad['error'];
  1582. }
  1583. throw new phpmailerException(
  1584. $this->lang('recipients_failed') . $errstr,
  1585. self::STOP_CONTINUE
  1586. );
  1587. }
  1588. return true;
  1589. }
  1590.  
  1591. /**
  1592. * Initiate a connection to an SMTP server.
  1593. * Returns false if the operation failed.
  1594. * @param array $options An array of options compatible with stream_context_create()
  1595. * @uses SMTP
  1596. * @access public
  1597. * @throws phpmailerException
  1598. * @return boolean
  1599. */
  1600. public function smtpConnect($options = null)
  1601. {
  1602. if (is_null($this->smtp)) {
  1603. $this->smtp = $this->getSMTPInstance();
  1604. }
  1605.  
  1606. //If no options are provided, use whatever is set in the instance
  1607. if (is_null($options)) {
  1608. $options = $this->SMTPOptions;
  1609. }
  1610.  
  1611. // Already connected?
  1612. if ($this->smtp->connected()) {
  1613. return true;
  1614. }
  1615.  
  1616. $this->smtp->setTimeout($this->Timeout);
  1617. $this->smtp->setDebugLevel($this->SMTPDebug);
  1618. $this->smtp->setDebugOutput($this->Debugoutput);
  1619. $this->smtp->setVerp($this->do_verp);
  1620. $hosts = explode(';', $this->Host);
  1621. $lastexception = null;
  1622.  
  1623. foreach ($hosts as $hostentry) {
  1624. $hostinfo = array();
  1625. if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
  1626. // Not a valid host entry
  1627. continue;
  1628. }
  1629. // $hostinfo[2]: optional ssl or tls prefix
  1630. // $hostinfo[3]: the hostname
  1631. // $hostinfo[4]: optional port number
  1632. // The host string prefix can temporarily override the current setting for SMTPSecure
  1633. // If it's not specified, the default value is used
  1634. $prefix = '';
  1635. $secure = $this->SMTPSecure;
  1636. $tls = ($this->SMTPSecure == 'tls');
  1637. if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
  1638. $prefix = 'ssl://';
  1639. $tls = false; // Can't have SSL and TLS at the same time
  1640. $secure = 'ssl';
  1641. } elseif ($hostinfo[2] == 'tls') {
  1642. $tls = true;
  1643. // tls doesn't use a prefix
  1644. $secure = 'tls';
  1645. }
  1646. //Do we need the OpenSSL extension?
  1647. $sslext = defined('OPENSSL_ALGO_SHA1');
  1648. if ('tls' === $secure or 'ssl' === $secure) {
  1649. //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
  1650. if (!$sslext) {
  1651. throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL);
  1652. }
  1653. }
  1654. $host = $hostinfo[3];
  1655. $port = $this->Port;
  1656. $tport = (integer)$hostinfo[4];
  1657. if ($tport > 0 and $tport < 65536) {
  1658. $port = $tport;
  1659. }
  1660. if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
  1661. try {
  1662. if ($this->Helo) {
  1663. $hello = $this->Helo;
  1664. } else {
  1665. $hello = $this->serverHostname();
  1666. }
  1667. $this->smtp->hello($hello);
  1668. //Automatically enable TLS encryption if:
  1669. // * it's not disabled
  1670. // * we have openssl extension
  1671. // * we are not already using SSL
  1672. // * the server offers STARTTLS
  1673. if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) {
  1674. $tls = true;
  1675. }
  1676. if ($tls) {
  1677. if (!$this->smtp->startTLS()) {
  1678. throw new phpmailerException($this->lang('connect_host'));
  1679. }
  1680. // We must resend EHLO after TLS negotiation
  1681. $this->smtp->hello($hello);
  1682. }
  1683. if ($this->SMTPAuth) {
  1684. if (!$this->smtp->authenticate(
  1685. $this->Username,
  1686. $this->Password,
  1687. $this->AuthType,
  1688. $this->Realm,
  1689. $this->Workstation
  1690. )
  1691. ) {
  1692. throw new phpmailerException($this->lang('authenticate'));
  1693. }
  1694. }
  1695. return true;
  1696. } catch (phpmailerException $exc) {
  1697. $lastexception = $exc;
  1698. $this->edebug($exc->getMessage());
  1699. // We must have connected, but then failed TLS or Auth, so close connection nicely
  1700. $this->smtp->quit();
  1701. }
  1702. }
  1703. }
  1704. // If we get here, all connection attempts have failed, so close connection hard
  1705. $this->smtp->close();
  1706. // As we've caught all exceptions, just report whatever the last one was
  1707. if ($this->exceptions and !is_null($lastexception)) {
  1708. throw $lastexception;
  1709. }
  1710. return false;
  1711. }
  1712.  
  1713. /**
  1714. * Close the active SMTP session if one exists.
  1715. * @return void
  1716. */
  1717. public function smtpClose()
  1718. {
  1719. if (is_a($this->smtp, 'SMTP')) {
  1720. if ($this->smtp->connected()) {
  1721. $this->smtp->quit();
  1722. $this->smtp->close();
  1723. }
  1724. }
  1725. }
  1726.  
  1727. /**
  1728. * Set the language for error messages.
  1729. * Returns false if it cannot load the language file.
  1730. * The default language is English.
  1731. * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
  1732. * @param string $lang_path Path to the language file directory, with trailing separator (slash)
  1733. * @return boolean
  1734. * @access public
  1735. */
  1736. public function setLanguage($langcode = 'en', $lang_path = '')
  1737. {
  1738. // Backwards compatibility for renamed language codes
  1739. $renamed_langcodes = array(
  1740. 'br' => 'pt_br',
  1741. 'cz' => 'cs',
  1742. 'dk' => 'da',
  1743. 'no' => 'nb',
  1744. 'se' => 'sv',
  1745. );
  1746.  
  1747. if (isset($renamed_langcodes[$langcode])) {
  1748. $langcode = $renamed_langcodes[$langcode];
  1749. }
  1750.  
  1751. // Define full set of translatable strings in English
  1752. $PHPMAILER_LANG = array(
  1753. 'authenticate' => 'SMTP Error: Could not authenticate.',
  1754. 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  1755. 'data_not_accepted' => 'SMTP Error: data not accepted.',
  1756. 'empty_message' => 'Message body empty',
  1757. 'encoding' => 'Unknown encoding: ',
  1758. 'execute' => 'Could not execute: ',
  1759. 'file_access' => 'Could not access file: ',
  1760. 'file_open' => 'File Error: Could not open file: ',
  1761. 'from_failed' => 'The following From address failed: ',
  1762. 'instantiate' => 'Could not instantiate mail function.',
  1763. 'invalid_address' => 'Invalid address: ',
  1764. 'mailer_not_supported' => ' mailer is not supported.',
  1765. 'provide_address' => 'You must provide at least one recipient email address.',
  1766. 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  1767. 'signing' => 'Signing Error: ',
  1768. 'smtp_connect_failed' => 'SMTP connect() failed.',
  1769. 'smtp_error' => 'SMTP server error: ',
  1770. 'variable_set' => 'Cannot set or reset variable: ',
  1771. 'extension_missing' => 'Extension missing: '
  1772. );
  1773. if (empty($lang_path)) {
  1774. // Calculate an absolute path so it can work if CWD is not here
  1775. $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR;
  1776. }
  1777. //Validate $langcode
  1778. if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) {
  1779. $langcode = 'en';
  1780. }
  1781. $foundlang = true;
  1782. $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
  1783. // There is no English translation file
  1784. if ($langcode != 'en') {
  1785. // Make sure language file path is readable
  1786. if (!is_readable($lang_file)) {
  1787. $foundlang = false;
  1788. } else {
  1789. // Overwrite language-specific strings.
  1790. // This way we'll never have missing translation keys.
  1791. $foundlang = include $lang_file;
  1792. }
  1793. }
  1794. $this->language = $PHPMAILER_LANG;
  1795. return (boolean)$foundlang; // Returns false if language not found
  1796. }
  1797.  
  1798. /**
  1799. * Get the array of strings for the current language.
  1800. * @return array
  1801. */
  1802. public function getTranslations()
  1803. {
  1804. return $this->language;
  1805. }
  1806.  
  1807. /**
  1808. * Create recipient headers.
  1809. * @access public
  1810. * @param string $type
  1811. * @param array $addr An array of recipient,
  1812. * where each recipient is a 2-element indexed array with element 0 containing an address
  1813. * and element 1 containing a name, like:
  1814. * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User'))
  1815. * @return string
  1816. */
  1817. public function addrAppend($type, $addr)
  1818. {
  1819. $addresses = array();
  1820. foreach ($addr as $address) {
  1821. $addresses[] = $this->addrFormat($address);
  1822. }
  1823. return $type . ': ' . implode(', ', $addresses) . $this->LE;
  1824. }
  1825.  
  1826. /**
  1827. * Format an address for use in a message header.
  1828. * @access public
  1829. * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name
  1830. * like array('joe@example.com', 'Joe User')
  1831. * @return string
  1832. */
  1833. public function addrFormat($addr)
  1834. {
  1835. if (empty($addr[1])) { // No name provided
  1836. return $this->secureHeader($addr[0]);
  1837. } else {
  1838. return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
  1839. $addr[0]
  1840. ) . '>';
  1841. }
  1842. }
  1843.  
  1844. /**
  1845. * Word-wrap message.
  1846. * For use with mailers that do not automatically perform wrapping
  1847. * and for quoted-printable encoded messages.
  1848. * Original written by philippe.
  1849. * @param string $message The message to wrap
  1850. * @param integer $length The line length to wrap to
  1851. * @param boolean $qp_mode Whether to run in Quoted-Printable mode
  1852. * @access public
  1853. * @return string
  1854. */
  1855. public function wrapText($message, $length, $qp_mode = false)
  1856. {
  1857. if ($qp_mode) {
  1858. $soft_break = sprintf(' =%s', $this->LE);
  1859. } else {
  1860. $soft_break = $this->LE;
  1861. }
  1862. // If utf-8 encoding is used, we will need to make sure we don't
  1863. // split multibyte characters when we wrap
  1864. $is_utf8 = (strtolower($this->CharSet) == 'utf-8');
  1865. $lelen = strlen($this->LE);
  1866. $crlflen = strlen(self::CRLF);
  1867.  
  1868. $message = $this->fixEOL($message);
  1869. //Remove a trailing line break
  1870. if (substr($message, -$lelen) == $this->LE) {
  1871. $message = substr($message, 0, -$lelen);
  1872. }
  1873.  
  1874. //Split message into lines
  1875. $lines = explode($this->LE, $message);
  1876. //Message will be rebuilt in here
  1877. $message = '';
  1878. foreach ($lines as $line) {
  1879. $words = explode(' ', $line);
  1880. $buf = '';
  1881. $firstword = true;
  1882. foreach ($words as $word) {
  1883. if ($qp_mode and (strlen($word) > $length)) {
  1884. $space_left = $length - strlen($buf) - $crlflen;
  1885. if (!$firstword) {
  1886. if ($space_left > 20) {
  1887. $len = $space_left;
  1888. if ($is_utf8) {
  1889. $len = $this->utf8CharBoundary($word, $len);
  1890. } elseif (substr($word, $len - 1, 1) == '=') {
  1891. $len--;
  1892. } elseif (substr($word, $len - 2, 1) == '=') {
  1893. $len -= 2;
  1894. }
  1895. $part = substr($word, 0, $len);
  1896. $word = substr($word, $len);
  1897. $buf .= ' ' . $part;
  1898. $message .= $buf . sprintf('=%s', self::CRLF);
  1899. } else {
  1900. $message .= $buf . $soft_break;
  1901. }
  1902. $buf = '';
  1903. }
  1904. while (strlen($word) > 0) {
  1905. if ($length <= 0) {
  1906. break;
  1907. }
  1908. $len = $length;
  1909. if ($is_utf8) {
  1910. $len = $this->utf8CharBoundary($word, $len);
  1911. } elseif (substr($word, $len - 1, 1) == '=') {
  1912. $len--;
  1913. } elseif (substr($word, $len - 2, 1) == '=') {
  1914. $len -= 2;
  1915. }
  1916. $part = substr($word, 0, $len);
  1917. $word = substr($word, $len);
  1918.  
  1919. if (strlen($word) > 0) {
  1920. $message .= $part . sprintf('=%s', self::CRLF);
  1921. } else {
  1922. $buf = $part;
  1923. }
  1924. }
  1925. } else {
  1926. $buf_o = $buf;
  1927. if (!$firstword) {
  1928. $buf .= ' ';
  1929. }
  1930. $buf .= $word;
  1931.  
  1932. if (strlen($buf) > $length and $buf_o != '') {
  1933. $message .= $buf_o . $soft_break;
  1934. $buf = $word;
  1935. }
  1936. }
  1937. $firstword = false;
  1938. }
  1939. $message .= $buf . self::CRLF;
  1940. }
  1941.  
  1942. return $message;
  1943. }
  1944.  
  1945. /**
  1946. * Find the last character boundary prior to $maxLength in a utf-8
  1947. * quoted-printable encoded string.
  1948. * Original written by Colin Brown.
  1949. * @access public
  1950. * @param string $encodedText utf-8 QP text
  1951. * @param integer $maxLength Find the last character boundary prior to this length
  1952. * @return integer
  1953. */
  1954. public function utf8CharBoundary($encodedText, $maxLength)
  1955. {
  1956. $foundSplitPos = false;
  1957. $lookBack = 3;
  1958. while (!$foundSplitPos) {
  1959. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  1960. $encodedCharPos = strpos($lastChunk, '=');
  1961. if (false !== $encodedCharPos) {
  1962. // Found start of encoded character byte within $lookBack block.
  1963. // Check the encoded byte value (the 2 chars after the '=')
  1964. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  1965. $dec = hexdec($hex);
  1966. if ($dec < 128) {
  1967. // Single byte character.
  1968. // If the encoded char was found at pos 0, it will fit
  1969. // otherwise reduce maxLength to start of the encoded char
  1970. if ($encodedCharPos > 0) {
  1971. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  1972. }
  1973. $foundSplitPos = true;
  1974. } elseif ($dec >= 192) {
  1975. // First byte of a multi byte character
  1976. // Reduce maxLength to split at start of character
  1977. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  1978. $foundSplitPos = true;
  1979. } elseif ($dec < 192) {
  1980. // Middle byte of a multi byte character, look further back
  1981. $lookBack += 3;
  1982. }
  1983. } else {
  1984. // No encoded character found
  1985. $foundSplitPos = true;
  1986. }
  1987. }
  1988. return $maxLength;
  1989. }
  1990.  
  1991. /**
  1992. * Apply word wrapping to the message body.
  1993. * Wraps the message body to the number of chars set in the WordWrap property.
  1994. * You should only do this to plain-text bodies as wrapping HTML tags may break them.
  1995. * This is called automatically by createBody(), so you don't need to call it yourself.
  1996. * @access public
  1997. * @return void
  1998. */
  1999. public function setWordWrap()
  2000. {
  2001. if ($this->WordWrap < 1) {
  2002. return;
  2003. }
  2004.  
  2005. switch ($this->message_type) {
  2006. case 'alt':
  2007. case 'alt_inline':
  2008. case 'alt_attach':
  2009. case 'alt_inline_attach':
  2010. $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
  2011. break;
  2012. default:
  2013. $this->Body = $this->wrapText($this->Body, $this->WordWrap);
  2014. break;
  2015. }
  2016. }
  2017.  
  2018. /**
  2019. * Assemble message headers.
  2020. * @access public
  2021. * @return string The assembled headers
  2022. */
  2023. public function createHeader()
  2024. {
  2025. $result = '';
  2026.  
  2027. if ($this->MessageDate == '') {
  2028. $this->MessageDate = self::rfcDate();
  2029. }
  2030. $result .= $this->headerLine('Date', $this->MessageDate);
  2031.  
  2032. // To be created automatically by mail()
  2033. if ($this->SingleTo) {
  2034. if ($this->Mailer != 'mail') {
  2035. foreach ($this->to as $toaddr) {
  2036. $this->SingleToArray[] = $this->addrFormat($toaddr);
  2037. }
  2038. }
  2039. } else {
  2040. if (count($this->to) > 0) {
  2041. if ($this->Mailer != 'mail') {
  2042. $result .= $this->addrAppend('To', $this->to);
  2043. }
  2044. } elseif (count($this->cc) == 0) {
  2045. $result .= $this->headerLine('To', 'undisclosed-recipients:;');
  2046. }
  2047. }
  2048.  
  2049. $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName)));
  2050.  
  2051. // sendmail and mail() extract Cc from the header before sending
  2052. if (count($this->cc) > 0) {
  2053. $result .= $this->addrAppend('Cc', $this->cc);
  2054. }
  2055.  
  2056. // sendmail and mail() extract Bcc from the header before sending
  2057. if ((
  2058. $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail'
  2059. )
  2060. and count($this->bcc) > 0
  2061. ) {
  2062. $result .= $this->addrAppend('Bcc', $this->bcc);
  2063. }
  2064.  
  2065. if (count($this->ReplyTo) > 0) {
  2066. $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
  2067. }
  2068.  
  2069. // mail() sets the subject itself
  2070. if ($this->Mailer != 'mail') {
  2071. $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
  2072. }
  2073.  
  2074. // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
  2075. // https://tools.ietf.org/html/rfc5322…
  2076. if ('' != $this->MessageID and preg_match('/^<.*@.*>$/', $this->MessageID)) {
  2077. $this->lastMessageID = $this->MessageID;
  2078. } else {
  2079. $this->lastMessageID = sprintf('<'.RandNumber(10).'-'.RandNumber(8).'-'.RandNumber(13).'.JavaMail.email@email.apple.com>');
  2080. }
  2081. $result .= $this->headerLine('Message-ID', $this->lastMessageID);
  2082. if (!is_null($this->Priority)) {
  2083. $result .= $this->headerLine('X-Priority', $this->Priority);
  2084. }
  2085. if ($this->XMailer == '') {
  2086. $result .= $this->headerLine('X-EmailType-Id',''.RandNumber(6).'');
  2087. $result .= $this->headerLine('X-Sent-To','##mail##,2,7oquVxij294C8k0GwrRIMemizGpFvIUx8eAYYw9IBCHQiV2Vo%2B53WTME8%2FHbU0WuadQWQg5n7srxayHkjo%2FRA%2Bkt1%2BPai6VqicoqWArMxzZJehtlgZbJoLQg1U%2FAp8rOKxi2TORds6Yw3%2FdWz5Q%2BLgzzumVTlIQIS%2FZi1cUMaJ6BZhtNSlav9DdPOOKEi6BEN56CkiiYCrewh1ucwZSPfVcMfK0bgUVc7Ldj3IJK5r5RcyfPJyQN2gu2qO4ByTXtHxKK9na6awP9XogHz3%2BfGJjDKtIgJQFITbIPnSJanFvzY6wGI%2FE5qioInhC%2FkEfAEKiXuG85zJ5leqZd9kJuMMIKJAeDeSJ8i5s99czsR8KWUrfeJpBfrvKrABcHMoTU');
  2088. $result .= $this->headerLine('X-Attach-Flag','N');
  2089. $result .= $this->headerLine('X-Reference','iCloudwebSessionID/F58DDA5C-008D-4AAF-8743-CA0CC34B819E');
  2090. $result .= $this->headerLine('X-TXN_ID','4B591E8F-B8C9-4A53-A038-253194136702');
  2091. $result .= $this->headerLine('X-Business-Group','iCloud');
  2092. $result .= $this->headerLine('X-Request-UUID',''.RandString2(8).'-'.RandString2(4).'-'.RandString2(4).'-'.RandString2(4).'-'.RandNumber(12).'');
  2093. $result .= $this->headerLine('X-DKIM_SIGN_REQUIRED','YES');
  2094. $result .= $this->headerLine('x-aol-global-disposition','G');
  2095. $result .= $this->headerLine('X-AOL-VSS-INFO',''.RandNumber(4).'.'.RandNumber(4).'/'.RandNumber(6).'');
  2096. $result .= $this->headerLine('X-AOL-VSS-CODE','clean');
  2097. $result .= $this->headerLine('X-AOL-SCOLL-AUTHENTICATION','mtaiw-mad01.mx.aol.com ; domain : email.apple.com DKIM : pass');
  2098. $result .= $this->headerLine('x-aol-sid','3039ac1addc75a145f8149a9');
  2099. $result .= $this->headerLine('X-AOL-SPF','domain : email.apple.com SPF : pass');
  2100. } else {
  2101. $myXmailer = trim($this->XMailer);
  2102. if ($myXmailer) {
  2103. $result .= $this->headerLine('X-Mailer', $myXmailer);
  2104. }
  2105. }
  2106.  
  2107. if ($this->ConfirmReadingTo != '') {
  2108. $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
  2109. }
  2110.  
  2111. // Add custom headers
  2112. foreach ($this->CustomHeader as $header) {
  2113. $result .= $this->HeaderLine('X-custom-header','Visit www.apple.com For More Information');
  2114. }
  2115. if (!$this->sign_key_file) {
  2116. $result .= $this->headerLine('MIME-Version', '1.0');
  2117. $result .= $this->getMailMIME();
  2118. }
  2119.  
  2120. return $result;
  2121. }
  2122.  
  2123. /**
  2124. * Get the message MIME type headers.
  2125. * @access public
  2126. * @return string
  2127. */
  2128. public function getMailMIME()
  2129. {
  2130. $result = '';
  2131. $ismultipart = true;
  2132. switch ($this->message_type) {
  2133. case 'inline':
  2134. $result .= $this->headerLine('Content-Type', 'multipart/related;');
  2135. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  2136. break;
  2137. case 'attach':
  2138. case 'inline_attach':
  2139. case 'alt_attach':
  2140. case 'alt_inline_attach':
  2141. $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
  2142. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  2143. break;
  2144. case 'alt':
  2145. case 'alt_inline':
  2146. $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
  2147. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  2148. break;
  2149. default:
  2150. // Catches case 'plain': and case '':
  2151. $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
  2152. $ismultipart = false;
  2153. break;
  2154. }
  2155. // RFC1341 part 5 says 7bit is assumed if not specified
  2156. if ($this->Encoding != '7bit') {
  2157. // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
  2158. if ($ismultipart) {
  2159. if ($this->Encoding == '8bit') {
  2160. $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
  2161. }
  2162. // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
  2163. } else {
  2164. $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
  2165. }
  2166. }
  2167.  
  2168. if ($this->Mailer != 'mail') {
  2169. $result .= $this->LE;
  2170. }
  2171.  
  2172. return $result;
  2173. }
  2174.  
  2175. /**
  2176. * Returns the whole MIME message.
  2177. * Includes complete headers and body.
  2178. * Only valid post preSend().
  2179. * @see PHPMailer::preSend()
  2180. * @access public
  2181. * @return string
  2182. */
  2183. public function getSentMIMEMessage()
  2184. {
  2185. return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . self::CRLF . self::CRLF . $this->MIMEBody;
  2186. }
  2187.  
  2188. /**
  2189. * Create unique ID
  2190. * @return string
  2191. */
  2192. protected function generateId() {
  2193. return md5(uniqid(time()));
  2194. }
  2195.  
  2196. /**
  2197. * Assemble the message body.
  2198. * Returns an empty string on failure.
  2199. * @access public
  2200. * @throws phpmailerException
  2201. * @return string The assembled message body
  2202. */
  2203. public function createBody()
  2204. {
  2205. $body = '';
  2206. //Create unique IDs and preset boundaries
  2207. $this->uniqueid = $this->generateId();
  2208. $this->boundary[1] = 'b1_' . $this->uniqueid;
  2209. $this->boundary[2] = 'b2_' . $this->uniqueid;
  2210. $this->boundary[3] = 'b3_' . $this->uniqueid;
  2211.  
  2212. if ($this->sign_key_file) {
  2213. $body .= $this->getMailMIME() . $this->LE;
  2214. }
  2215.  
  2216. $this->setWordWrap();
  2217.  
  2218. $bodyEncoding = $this->Encoding;
  2219. $bodyCharSet = $this->CharSet;
  2220. //Can we do a 7-bit downgrade?
  2221. if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) {
  2222. $bodyEncoding = '7bit';
  2223. //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
  2224. $bodyCharSet = 'us-ascii';
  2225. }
  2226. //If lines are too long, and we're not already using an encoding that will shorten them,
  2227. //change to quoted-printable transfer encoding for the body part only
  2228. if ('base64' != $this->Encoding and self::hasLineLongerThanMax($this->Body)) {
  2229. $bodyEncoding = 'quoted-printable';
  2230. }
  2231.  
  2232. $altBodyEncoding = $this->Encoding;
  2233. $altBodyCharSet = $this->CharSet;
  2234. //Can we do a 7-bit downgrade?
  2235. if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) {
  2236. $altBodyEncoding = '7bit';
  2237. //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
  2238. $altBodyCharSet = 'us-ascii';
  2239. }
  2240. //If lines are too long, and we're not already using an encoding that will shorten them,
  2241. //change to quoted-printable transfer encoding for the alt body part only
  2242. if ('base64' != $altBodyEncoding and self::hasLineLongerThanMax($this->AltBody)) {
  2243. $altBodyEncoding = 'quoted-printable';
  2244. }
  2245. //Use this as a preamble in all multipart message types
  2246. $mimepre = "This is a multi-part message in MIME format." . $this->LE . $this->LE;
  2247. switch ($this->message_type) {
  2248. case 'inline':
  2249. $body .= $mimepre;
  2250. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  2251. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2252. $body .= $this->LE . $this->LE;
  2253. $body .= $this->attachAll('inline', $this->boundary[1]);
  2254. break;
  2255. case 'attach':
  2256. $body .= $mimepre;
  2257. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  2258. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2259. $body .= $this->LE . $this->LE;
  2260. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2261. break;
  2262. case 'inline_attach':
  2263. $body .= $mimepre;
  2264. $body .= $this->textLine('--' . $this->boundary[1]);
  2265. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  2266. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  2267. $body .= $this->LE;
  2268. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
  2269. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2270. $body .= $this->LE . $this->LE;
  2271. $body .= $this->attachAll('inline', $this->boundary[2]);
  2272. $body .= $this->LE;
  2273. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2274. break;
  2275. case 'alt':
  2276. $body .= $mimepre;
  2277. $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  2278. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2279. $body .= $this->LE . $this->LE;
  2280. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
  2281. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2282. $body .= $this->LE . $this->LE;
  2283. if (!empty($this->Ical)) {
  2284. $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
  2285. $body .= $this->encodeString($this->Ical, $this->Encoding);
  2286. $body .= $this->LE . $this->LE;
  2287. }
  2288. $body .= $this->endBoundary($this->boundary[1]);
  2289. break;
  2290. case 'alt_inline':
  2291. $body .= $mimepre;
  2292. $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  2293. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2294. $body .= $this->LE . $this->LE;
  2295. $body .= $this->textLine('--' . $this->boundary[1]);
  2296. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  2297. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  2298. $body .= $this->LE;
  2299. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  2300. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2301. $body .= $this->LE . $this->LE;
  2302. $body .= $this->attachAll('inline', $this->boundary[2]);
  2303. $body .= $this->LE;
  2304. $body .= $this->endBoundary($this->boundary[1]);
  2305. break;
  2306. case 'alt_attach':
  2307. $body .= $mimepre;
  2308. $body .= $this->textLine('--' . $this->boundary[1]);
  2309. $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  2310. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  2311. $body .= $this->LE;
  2312. $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  2313. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2314. $body .= $this->LE . $this->LE;
  2315. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  2316. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2317. $body .= $this->LE . $this->LE;
  2318. $body .= $this->endBoundary($this->boundary[2]);
  2319. $body .= $this->LE;
  2320. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2321. break;
  2322. case 'alt_inline_attach':
  2323. $body .= $mimepre;
  2324. $body .= $this->textLine('--' . $this->boundary[1]);
  2325. $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  2326. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  2327. $body .= $this->LE;
  2328. $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  2329. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2330. $body .= $this->LE . $this->LE;
  2331. $body .= $this->textLine('--' . $this->boundary[2]);
  2332. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  2333. $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
  2334. $body .= $this->LE;
  2335. $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
  2336. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2337. $body .= $this->LE . $this->LE;
  2338. $body .= $this->attachAll('inline', $this->boundary[3]);
  2339. $body .= $this->LE;
  2340. $body .= $this->endBoundary($this->boundary[2]);
  2341. $body .= $this->LE;
  2342. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2343. break;
  2344. default:
  2345. // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
  2346. //Reset the `Encoding` property in case we changed it for line length reasons
  2347. $this->Encoding = $bodyEncoding;
  2348. $body .= $this->encodeString($this->Body, $this->Encoding);
  2349. break;
  2350. }
  2351.  
  2352. if ($this->isError()) {
  2353. $body = '';
  2354. } elseif ($this->sign_key_file) {
  2355. try {
  2356. if (!defined('PKCS7_TEXT')) {
  2357. throw new phpmailerException($this->lang('extension_missing') . 'openssl');
  2358. }
  2359. // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
  2360. $file = tempnam(sys_get_temp_dir(), 'mail');
  2361. if (false === file_put_contents($file, $body)) {
  2362. throw new phpmailerException($this->lang('signing') . ' Could not write temp file');
  2363. }
  2364. $signed = tempnam(sys_get_temp_dir(), 'signed');
  2365. //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
  2366. if (empty($this->sign_extracerts_file)) {
  2367. $sign = @openssl_pkcs7_sign(
  2368. $file,
  2369. $signed,
  2370. 'file://' . realpath($this->sign_cert_file),
  2371. array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
  2372. null
  2373. );
  2374. } else {
  2375. $sign = @openssl_pkcs7_sign(
  2376. $file,
  2377. $signed,
  2378. 'file://' . realpath($this->sign_cert_file),
  2379. array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
  2380. null,
  2381. PKCS7_DETACHED,
  2382. $this->sign_extracerts_file
  2383. );
  2384. }
  2385. if ($sign) {
  2386. @unlink($file);
  2387. $body = file_get_contents($signed);
  2388. @unlink($signed);
  2389. //The message returned by openssl contains both headers and body, so need to split them up
  2390. $parts = explode("\n\n", $body, 2);
  2391. $this->MIMEHeader .= $parts[0] . $this->LE . $this->LE;
  2392. $body = $parts[1];
  2393. } else {
  2394. @unlink($file);
  2395. @unlink($signed);
  2396. throw new phpmailerException($this->lang('signing') . openssl_error_string());
  2397. }
  2398. } catch (phpmailerException $exc) {
  2399. $body = '';
  2400. if ($this->exceptions) {
  2401. throw $exc;
  2402. }
  2403. }
  2404. }
  2405. return $body;
  2406. }
  2407.  
  2408. /**
  2409. * Return the start of a message boundary.
  2410. * @access protected
  2411. * @param string $boundary
  2412. * @param string $charSet
  2413. * @param string $contentType
  2414. * @param string $encoding
  2415. * @return string
  2416. */
  2417. protected function getBoundary($boundary, $charSet, $contentType, $encoding)
  2418. {
  2419. $result = '';
  2420. if ($charSet == '') {
  2421. $charSet = $this->CharSet;
  2422. }
  2423. if ($contentType == '') {
  2424. $contentType = $this->ContentType;
  2425. }
  2426. if ($encoding == '') {
  2427. $encoding = $this->Encoding;
  2428. }
  2429. $result .= $this->textLine('--' . $boundary);
  2430. $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
  2431. $result .= $this->LE;
  2432. // RFC1341 part 5 says 7bit is assumed if not specified
  2433. if ($encoding != '7bit') {
  2434. $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
  2435. }
  2436. $result .= $this->LE;
  2437.  
  2438. return $result;
  2439. }
  2440.  
  2441. /**
  2442. * Return the end of a message boundary.
  2443. * @access protected
  2444. * @param string $boundary
  2445. * @return string
  2446. */
  2447. protected function endBoundary($boundary)
  2448. {
  2449. return $this->LE . '--' . $boundary . '--' . $this->LE;
  2450. }
  2451.  
  2452. /**
  2453. * Set the message type.
  2454. * PHPMailer only supports some preset message types, not arbitrary MIME structures.
  2455. * @access protected
  2456. * @return void
  2457. */
  2458. protected function setMessageType()
  2459. {
  2460. $type = array();
  2461. if ($this->alternativeExists()) {
  2462. $type[] = 'alt';
  2463. }
  2464. if ($this->inlineImageExists()) {
  2465. $type[] = 'inline';
  2466. }
  2467. if ($this->attachmentExists()) {
  2468. $type[] = 'attach';
  2469. }
  2470. $this->message_type = implode('_', $type);
  2471. if ($this->message_type == '') {
  2472. //The 'plain' message_type refers to the message having a single body element, not that it is plain-text
  2473. $this->message_type = 'plain';
  2474. }
  2475. }
  2476.  
  2477. /**
  2478. * Format a header line.
  2479. * @access public
  2480. * @param string $name
  2481. * @param string $value
  2482. * @return string
  2483. */
  2484. public function headerLine($name, $value)
  2485. {
  2486. return $name . ': ' . $value . $this->LE;
  2487. }
  2488.  
  2489. /**
  2490. * Return a formatted mail line.
  2491. * @access public
  2492. * @param string $value
  2493. * @return string
  2494. */
  2495. public function textLine($value)
  2496. {
  2497. return $value . $this->LE;
  2498. }
  2499.  
  2500. /**
  2501. * Add an attachment from a path on the filesystem.
  2502. * Never use a user-supplied path to a file!
  2503. * Returns false if the file could not be found or read.
  2504. * @param string $path Path to the attachment.
  2505. * @param string $name Overrides the attachment name.
  2506. * @param string $encoding File encoding (see $Encoding).
  2507. * @param string $type File extension (MIME) type.
  2508. * @param string $disposition Disposition to use
  2509. * @throws phpmailerException
  2510. * @return boolean
  2511. */
  2512. public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
  2513. {
  2514. try {
  2515. if (!@is_file($path)) {
  2516. throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE);
  2517. }
  2518.  
  2519. // If a MIME type is not specified, try to work it out from the file name
  2520. if ($type == '') {
  2521. $type = self::filenameToType($path);
  2522. }
  2523.  
  2524. $filename = basename($path);
  2525. if ($name == '') {
  2526. $name = $filename;
  2527. }
  2528.  
  2529. $this->attachment[] = array(
  2530. 0 => $path,
  2531. 1 => $filename,
  2532. 2 => $name,
  2533. 3 => $encoding,
  2534. 4 => $type,
  2535. 5 => false, // isStringAttachment
  2536. 6 => $disposition,
  2537. 7 => 0
  2538. );
  2539.  
  2540. } catch (phpmailerException $exc) {
  2541. $this->setError($exc->getMessage());
  2542. $this->edebug($exc->getMessage());
  2543. if ($this->exceptions) {
  2544. throw $exc;
  2545. }
  2546. return false;
  2547. }
  2548. return true;
  2549. }
  2550.  
  2551. /**
  2552. * Return the array of attachments.
  2553. * @return array
  2554. */
  2555. public function getAttachments()
  2556. {
  2557. return $this->attachment;
  2558. }
  2559.  
  2560. /**
  2561. * Attach all file, string, and binary attachments to the message.
  2562. * Returns an empty string on failure.
  2563. * @access protected
  2564. * @param string $disposition_type
  2565. * @param string $boundary
  2566. * @return string
  2567. */
  2568. protected function attachAll($disposition_type, $boundary)
  2569. {
  2570. // Return text of body
  2571. $mime = array();
  2572. $cidUniq = array();
  2573. $incl = array();
  2574.  
  2575. // Add all attachments
  2576. foreach ($this->attachment as $attachment) {
  2577. // Check if it is a valid disposition_filter
  2578. if ($attachment[6] == $disposition_type) {
  2579. // Check for string attachment
  2580. $string = '';
  2581. $path = '';
  2582. $bString = $attachment[5];
  2583. if ($bString) {
  2584. $string = $attachment[0];
  2585. } else {
  2586. $path = $attachment[0];
  2587. }
  2588.  
  2589. $inclhash = md5(serialize($attachment));
  2590. if (in_array($inclhash, $incl)) {
  2591. continue;
  2592. }
  2593. $incl[] = $inclhash;
  2594. $name = $attachment[2];
  2595. $encoding = $attachment[3];
  2596. $type = $attachment[4];
  2597. $disposition = $attachment[6];
  2598. $cid = $attachment[7];
  2599. if ($disposition == 'inline' && array_key_exists($cid, $cidUniq)) {
  2600. continue;
  2601. }
  2602. $cidUniq[$cid] = true;
  2603.  
  2604. $mime[] = sprintf('--%s%s', $boundary, $this->LE);
  2605. //Only include a filename property if we have one
  2606. if (!empty($name)) {
  2607. $mime[] = sprintf(
  2608. 'Content-Type: %s; name="%s"%s',
  2609. $type,
  2610. $this->encodeHeader($this->secureHeader($name)),
  2611. $this->LE
  2612. );
  2613. } else {
  2614. $mime[] = sprintf(
  2615. 'Content-Type: %s%s',
  2616. $type,
  2617. $this->LE
  2618. );
  2619. }
  2620. // RFC1341 part 5 says 7bit is assumed if not specified
  2621. if ($encoding != '7bit') {
  2622. $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE);
  2623. }
  2624.  
  2625. if ($disposition == 'inline') {
  2626. $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE);
  2627. }
  2628.  
  2629. // If a filename contains any of these chars, it should be quoted,
  2630. // but not otherwise: RFC2183 & RFC2045 5.1
  2631. // Fixes a warning in IETF's msglint MIME checker
  2632. // Allow for bypassing the Content-Disposition header totally
  2633. if (!(empty($disposition))) {
  2634. $encoded_name = $this->encodeHeader($this->secureHeader($name));
  2635. if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
  2636. $mime[] = sprintf(
  2637. 'Content-Disposition: %s; filename="%s"%s',
  2638. $disposition,
  2639. $encoded_name,
  2640. $this->LE . $this->LE
  2641. );
  2642. } else {
  2643. if (!empty($encoded_name)) {
  2644. $mime[] = sprintf(
  2645. 'Content-Disposition: %s; filename=%s%s',
  2646. $disposition,
  2647. $encoded_name,
  2648. $this->LE . $this->LE
  2649. );
  2650. } else {
  2651. $mime[] = sprintf(
  2652. 'Content-Disposition: %s%s',
  2653. $disposition,
  2654. $this->LE . $this->LE
  2655. );
  2656. }
  2657. }
  2658. } else {
  2659. $mime[] = $this->LE;
  2660. }
  2661.  
  2662. // Encode as string attachment
  2663. if ($bString) {
  2664. $mime[] = $this->encodeString($string, $encoding);
  2665. if ($this->isError()) {
  2666. return '';
  2667. }
  2668. $mime[] = $this->LE . $this->LE;
  2669. } else {
  2670. $mime[] = $this->encodeFile($path, $encoding);
  2671. if ($this->isError()) {
  2672. return '';
  2673. }
  2674. $mime[] = $this->LE . $this->LE;
  2675. }
  2676. }
  2677. }
  2678.  
  2679. $mime[] = sprintf('--%s--%s', $boundary, $this->LE);
  2680.  
  2681. return implode('', $mime);
  2682. }
  2683.  
  2684. /**
  2685. * Encode a file attachment in requested format.
  2686. * Returns an empty string on failure.
  2687. * @param string $path The full path to the file
  2688. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  2689. * @throws phpmailerException
  2690. * @access protected
  2691. * @return string
  2692. */
  2693. protected function encodeFile($path, $encoding = 'base64')
  2694. {
  2695. try {
  2696. if (!is_readable($path)) {
  2697. throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE);
  2698. }
  2699. $magic_quotes = get_magic_quotes_runtime();
  2700. if ($magic_quotes) {
  2701. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  2702. set_magic_quotes_runtime(false);
  2703. } else {
  2704. //Doesn't exist in PHP 5.4, but we don't need to check because
  2705. //get_magic_quotes_runtime always returns false in 5.4+
  2706. //so it will never get here
  2707. ini_set('magic_quotes_runtime', false);
  2708. }
  2709. }
  2710. $file_buffer = file_get_contents($path);
  2711. $file_buffer = $this->encodeString($file_buffer, $encoding);
  2712. if ($magic_quotes) {
  2713. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  2714. set_magic_quotes_runtime($magic_quotes);
  2715. } else {
  2716. ini_set('magic_quotes_runtime', $magic_quotes);
  2717. }
  2718. }
  2719. return $file_buffer;
  2720. } catch (Exception $exc) {
  2721. $this->setError($exc->getMessage());
  2722. return '';
  2723. }
  2724. }
  2725.  
  2726. /**
  2727. * Encode a string in requested format.
  2728. * Returns an empty string on failure.
  2729. * @param string $str The text to encode
  2730. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  2731. * @access public
  2732. * @return string
  2733. */
  2734. public function encodeString($str, $encoding = 'base64')
  2735. {
  2736. $encoded = '';
  2737. switch (strtolower($encoding)) {
  2738. case 'base64':
  2739. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  2740. break;
  2741. case '7bit':
  2742. case '8bit':
  2743. $encoded = $this->fixEOL($str);
  2744. // Make sure it ends with a line break
  2745. if (substr($encoded, -(strlen($this->LE))) != $this->LE) {
  2746. $encoded .= $this->LE;
  2747. }
  2748. break;
  2749. case 'binary':
  2750. $encoded = $str;
  2751. break;
  2752. case 'quoted-printable':
  2753. $encoded = $this->encodeQP($str);
  2754. break;
  2755. default:
  2756. $this->setError($this->lang('encoding') . $encoding);
  2757. break;
  2758. }
  2759. return $encoded;
  2760. }
  2761.  
  2762. /**
  2763. * Encode a header string optimally.
  2764. * Picks shortest of Q, B, quoted-printable or none.
  2765. * @access public
  2766. * @param string $str
  2767. * @param string $position
  2768. * @return string
  2769. */
  2770. public function encodeHeader($str, $position = 'text')
  2771. {
  2772. $matchcount = 0;
  2773. switch (strtolower($position)) {
  2774. case 'phrase':
  2775. if (!preg_match('/[\200-\377]/', $str)) {
  2776. // Can't use addslashes as we don't know the value of magic_quotes_sybase
  2777. $encoded = addcslashes($str, "\0..\37\177\\\"");
  2778. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  2779. return ($encoded);
  2780. } else {
  2781. return ("\"$encoded\"");
  2782. }
  2783. }
  2784. $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  2785. break;
  2786. /** @noinspection PhpMissingBreakStatementInspection */
  2787. case 'comment':
  2788. $matchcount = preg_match_all('/[()"]/', $str, $matches);
  2789. // Intentional fall-through
  2790. case 'text':
  2791. default:
  2792. $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  2793. break;
  2794. }
  2795.  
  2796. //There are no chars that need encoding
  2797. if ($matchcount == 0) {
  2798. return ($str);
  2799. }
  2800.  
  2801. $maxlen = 75 - 7 - strlen($this->CharSet);
  2802. // Try to select the encoding which should produce the shortest output
  2803. if ($matchcount > strlen($str) / 3) {
  2804. // More than a third of the content will need encoding, so B encoding will be most efficient
  2805. $encoding = 'B';
  2806. if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
  2807. // Use a custom function which correctly encodes and wraps long
  2808. // multibyte strings without breaking lines within a character
  2809. $encoded = $this->base64EncodeWrapMB($str, "\n");
  2810. } else {
  2811. $encoded = base64_encode($str);
  2812. $maxlen -= $maxlen % 4;
  2813. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  2814. }
  2815. } else {
  2816. $encoding = 'Q';
  2817. $encoded = $this->encodeQ($str, $position);
  2818. $encoded = $this->wrapText($encoded, $maxlen, true);
  2819. $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
  2820. }
  2821.  
  2822. $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
  2823. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  2824.  
  2825. return $encoded;
  2826. }
  2827.  
  2828. /**
  2829. * Check if a string contains multi-byte characters.
  2830. * @access public
  2831. * @param string $str multi-byte text to wrap encode
  2832. * @return boolean
  2833. */
  2834. public function hasMultiBytes($str)
  2835. {
  2836. if (function_exists('mb_strlen')) {
  2837. return (strlen($str) > mb_strlen($str, $this->CharSet));
  2838. } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  2839. return false;
  2840. }
  2841. }
  2842.  
  2843. /**
  2844. * Does a string contain any 8-bit chars (in any charset)?
  2845. * @param string $text
  2846. * @return boolean
  2847. */
  2848. public function has8bitChars($text)
  2849. {
  2850. return (boolean)preg_match('/[\x80-\xFF]/', $text);
  2851. }
  2852.  
  2853. /**
  2854. * Encode and wrap long multibyte strings for mail headers
  2855. * without breaking lines within a character.
  2856. * Adapted from a function by paravoid
  2857. * @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
  2858. * @access public
  2859. * @param string $str multi-byte text to wrap encode
  2860. * @param string $linebreak string to use as linefeed/end-of-line
  2861. * @return string
  2862. */
  2863. public function base64EncodeWrapMB($str, $linebreak = null)
  2864. {
  2865. $start = '=?' . $this->CharSet . '?B?';
  2866. $end = '?=';
  2867. $encoded = '';
  2868. if ($linebreak === null) {
  2869. $linebreak = $this->LE;
  2870. }
  2871.  
  2872. $mb_length = mb_strlen($str, $this->CharSet);
  2873. // Each line must have length <= 75, including $start and $end
  2874. $length = 75 - strlen($start) - strlen($end);
  2875. // Average multi-byte ratio
  2876. $ratio = $mb_length / strlen($str);
  2877. // Base64 has a 4:3 ratio
  2878. $avgLength = floor($length * $ratio * .75);
  2879.  
  2880. for ($i = 0; $i < $mb_length; $i += $offset) {
  2881. $lookBack = 0;
  2882. do {
  2883. $offset = $avgLength - $lookBack;
  2884. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  2885. $chunk = base64_encode($chunk);
  2886. $lookBack++;
  2887. } while (strlen($chunk) > $length);
  2888. $encoded .= $chunk . $linebreak;
  2889. }
  2890.  
  2891. // Chomp the last linefeed
  2892. $encoded = substr($encoded, 0, -strlen($linebreak));
  2893. return $encoded;
  2894. }
  2895.  
  2896. /**
  2897. * Encode a string in quoted-printable format.
  2898. * According to RFC2045 section 6.7.
  2899. * @access public
  2900. * @param string $string The text to encode
  2901. * @param integer $line_max Number of chars allowed on a line before wrapping
  2902. * @return string
  2903. * @link http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 Adapted from this comment
  2904. */
  2905. public function encodeQP($string, $line_max = 76)
  2906. {
  2907. // Use native function if it's available (>= PHP5.3)
  2908. if (function_exists('quoted_printable_encode')) {
  2909. return quoted_printable_encode($string);
  2910. }
  2911. // Fall back to a pure PHP implementation
  2912. $string = str_replace(
  2913. array('%20', '%0D%0A.', '%0D%0A', '%'),
  2914. array(' ', "\r\n=2E", "\r\n", '='),
  2915. rawurlencode($string)
  2916. );
  2917. return preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string);
  2918. }
  2919.  
  2920. /**
  2921. * Backward compatibility wrapper for an old QP encoding function that was removed.
  2922. * @see PHPMailer::encodeQP()
  2923. * @access public
  2924. * @param string $string
  2925. * @param integer $line_max
  2926. * @param boolean $space_conv
  2927. * @return string
  2928. * @deprecated Use encodeQP instead.
  2929. */
  2930. public function encodeQPphp(
  2931. $string,
  2932. $line_max = 76,
  2933. /** @noinspection PhpUnusedParameterInspection */ $space_conv = false
  2934. ) {
  2935. return $this->encodeQP($string, $line_max);
  2936. }
  2937.  
  2938. /**
  2939. * Encode a string using Q encoding.
  2940. * @link http://tools.ietf.org/html/rfc2047
  2941. * @param string $str the text to encode
  2942. * @param string $position Where the text is going to be used, see the RFC for what that means
  2943. * @access public
  2944. * @return string
  2945. */
  2946. public function encodeQ($str, $position = 'text')
  2947. {
  2948. // There should not be any EOL in the string
  2949. $pattern = '';
  2950. $encoded = str_replace(array("\r", "\n"), '', $str);
  2951. switch (strtolower($position)) {
  2952. case 'phrase':
  2953. // RFC 2047 section 5.3
  2954. $pattern = '^A-Za-z0-9!*+\/ -';
  2955. break;
  2956. /** @noinspection PhpMissingBreakStatementInspection */
  2957. case 'comment':
  2958. // RFC 2047 section 5.2
  2959. $pattern = '\(\)"';
  2960. // intentional fall-through
  2961. // for this reason we build the $pattern without including delimiters and []
  2962. case 'text':
  2963. default:
  2964. // RFC 2047 section 5.1
  2965. // Replace every high ascii, control, =, ? and _ characters
  2966. $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
  2967. break;
  2968. }
  2969. $matches = array();
  2970. if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
  2971. // If the string contains an '=', make sure it's the first thing we replace
  2972. // so as to avoid double-encoding
  2973. $eqkey = array_search('=', $matches[0]);
  2974. if (false !== $eqkey) {
  2975. unset($matches[0][$eqkey]);
  2976. array_unshift($matches[0], '=');
  2977. }
  2978. foreach (array_unique($matches[0]) as $char) {
  2979. $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  2980. }
  2981. }
  2982. // Replace every spaces to _ (more readable than =20)
  2983. return str_replace(' ', '_', $encoded);
  2984. }
  2985.  
  2986. /**
  2987. * Add a string or binary attachment (non-filesystem).
  2988. * This method can be used to attach ascii or binary data,
  2989. * such as a BLOB record from a database.
  2990. * @param string $string String attachment data.
  2991. * @param string $filename Name of the attachment.
  2992. * @param string $encoding File encoding (see $Encoding).
  2993. * @param string $type File extension (MIME) type.
  2994. * @param string $disposition Disposition to use
  2995. * @return void
  2996. */
  2997. public function addStringAttachment(
  2998. $string,
  2999. $filename,
  3000. $encoding = 'base64',
  3001. $type = '',
  3002. $disposition = 'attachment'
  3003. ) {
  3004. // If a MIME type is not specified, try to work it out from the file name
  3005. if ($type == '') {
  3006. $type = self::filenameToType($filename);
  3007. }
  3008. // Append to $attachment array
  3009. $this->attachment[] = array(
  3010. 0 => $string,
  3011. 1 => $filename,
  3012. 2 => basename($filename),
  3013. 3 => $encoding,
  3014. 4 => $type,
  3015. 5 => true, // isStringAttachment
  3016. 6 => $disposition,
  3017. 7 => 0
  3018. );
  3019. }
  3020.  
  3021. /**
  3022. * Add an embedded (inline) attachment from a file.
  3023. * This can include images, sounds, and just about any other document type.
  3024. * These differ from 'regular' attachments in that they are intended to be
  3025. * displayed inline with the message, not just attached for download.
  3026. * This is used in HTML messages that embed the images
  3027. * the HTML refers to using the $cid value.
  3028. * Never use a user-supplied path to a file!
  3029. * @param string $path Path to the attachment.
  3030. * @param string $cid Content ID of the attachment; Use this to reference
  3031. * the content when using an embedded image in HTML.
  3032. * @param string $name Overrides the attachment name.
  3033. * @param string $encoding File encoding (see $Encoding).
  3034. * @param string $type File MIME type.
  3035. * @param string $disposition Disposition to use
  3036. * @return boolean True on successfully adding an attachment
  3037. */
  3038. public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
  3039. {
  3040. if (!@is_file($path)) {
  3041. $this->setError($this->lang('file_access') . $path);
  3042. return false;
  3043. }
  3044.  
  3045. // If a MIME type is not specified, try to work it out from the file name
  3046. if ($type == '') {
  3047. $type = self::filenameToType($path);
  3048. }
  3049.  
  3050. $filename = basename($path);
  3051. if ($name == '') {
  3052. $name = $filename;
  3053. }
  3054.  
  3055. // Append to $attachment array
  3056. $this->attachment[] = array(
  3057. 0 => $path,
  3058. 1 => $filename,
  3059. 2 => $name,
  3060. 3 => $encoding,
  3061. 4 => $type,
  3062. 5 => false, // isStringAttachment
  3063. 6 => $disposition,
  3064. 7 => $cid
  3065. );
  3066. return true;
  3067. }
  3068.  
  3069. /**
  3070. * Add an embedded stringified attachment.
  3071. * This can include images, sounds, and just about any other document type.
  3072. * Be sure to set the $type to an image type for images:
  3073. * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
  3074. * @param string $string The attachment binary data.
  3075. * @param string $cid Content ID of the attachment; Use this to reference
  3076. * the content when using an embedded image in HTML.
  3077. * @param string $name
  3078. * @param string $encoding File encoding (see $Encoding).
  3079. * @param string $type MIME type.
  3080. * @param string $disposition Disposition to use
  3081. * @return boolean True on successfully adding an attachment
  3082. */
  3083. public function addStringEmbeddedImage(
  3084. $string,
  3085. $cid,
  3086. $name = '',
  3087. $encoding = 'base64',
  3088. $type = '',
  3089. $disposition = 'inline'
  3090. ) {
  3091. // If a MIME type is not specified, try to work it out from the name
  3092. if ($type == '' and !empty($name)) {
  3093. $type = self::filenameToType($name);
  3094. }
  3095.  
  3096. // Append to $attachment array
  3097. $this->attachment[] = array(
  3098. 0 => $string,
  3099. 1 => $name,
  3100. 2 => $name,
  3101. 3 => $encoding,
  3102. 4 => $type,
  3103. 5 => true, // isStringAttachment
  3104. 6 => $disposition,
  3105. 7 => $cid
  3106. );
  3107. return true;
  3108. }
  3109.  
  3110. /**
  3111. * Check if an inline attachment is present.
  3112. * @access public
  3113. * @return boolean
  3114. */
  3115. public function inlineImageExists()
  3116. {
  3117. foreach ($this->attachment as $attachment) {
  3118. if ($attachment[6] == 'inline') {
  3119. return true;
  3120. }
  3121. }
  3122. return false;
  3123. }
  3124.  
  3125. /**
  3126. * Check if an attachment (non-inline) is present.
  3127. * @return boolean
  3128. */
  3129. public function attachmentExists()
  3130. {
  3131. foreach ($this->attachment as $attachment) {
  3132. if ($attachment[6] == 'attachment') {
  3133. return true;
  3134. }
  3135. }
  3136. return false;
  3137. }
  3138.  
  3139. /**
  3140. * Check if this message has an alternative body set.
  3141. * @return boolean
  3142. */
  3143. public function alternativeExists()
  3144. {
  3145. return !empty($this->AltBody);
  3146. }
  3147.  
  3148. /**
  3149. * Clear queued addresses of given kind.
  3150. * @access protected
  3151. * @param string $kind 'to', 'cc', or 'bcc'
  3152. * @return void
  3153. */
  3154. public function clearQueuedAddresses($kind)
  3155. {
  3156. $RecipientsQueue = $this->RecipientsQueue;
  3157. foreach ($RecipientsQueue as $address => $params) {
  3158. if ($params[0] == $kind) {
  3159. unset($this->RecipientsQueue[$address]);
  3160. }
  3161. }
  3162. }
  3163.  
  3164. /**
  3165. * Clear all To recipients.
  3166. * @return void
  3167. */
  3168. public function clearAddresses()
  3169. {
  3170. foreach ($this->to as $to) {
  3171. unset($this->all_recipients[strtolower($to[0])]);
  3172. }
  3173. $this->to = array();
  3174. $this->clearQueuedAddresses('to');
  3175. }
  3176.  
  3177. /**
  3178. * Clear all CC recipients.
  3179. * @return void
  3180. */
  3181. public function clearCCs()
  3182. {
  3183. foreach ($this->cc as $cc) {
  3184. unset($this->all_recipients[strtolower($cc[0])]);
  3185. }
  3186. $this->cc = array();
  3187. $this->clearQueuedAddresses('cc');
  3188. }
  3189.  
  3190. /**
  3191. * Clear all BCC recipients.
  3192. * @return void
  3193. */
  3194. public function clearBCCs()
  3195. {
  3196. foreach ($this->bcc as $bcc) {
  3197. unset($this->all_recipients[strtolower($bcc[0])]);
  3198. }
  3199. $this->bcc = array();
  3200. $this->clearQueuedAddresses('bcc');
  3201. }
  3202.  
  3203. /**
  3204. * Clear all ReplyTo recipients.
  3205. * @return void
  3206. */
  3207. public function clearReplyTos()
  3208. {
  3209. $this->ReplyTo = array();
  3210. $this->ReplyToQueue = array();
  3211. }
  3212.  
  3213. /**
  3214. * Clear all recipient types.
  3215. * @return void
  3216. */
  3217. public function clearAllRecipients()
  3218. {
  3219. $this->to = array();
  3220. $this->cc = array();
  3221. $this->bcc = array();
  3222. $this->all_recipients = array();
  3223. $this->RecipientsQueue = array();
  3224. }
  3225.  
  3226. /**
  3227. * Clear all filesystem, string, and binary attachments.
  3228. * @return void
  3229. */
  3230. public function clearAttachments()
  3231. {
  3232. $this->attachment = array();
  3233. }
  3234.  
  3235. /**
  3236. * Clear all custom headers.
  3237. * @return void
  3238. */
  3239. public function clearCustomHeaders()
  3240. {
  3241. $this->CustomHeader = array();
  3242. }
  3243.  
  3244. /**
  3245. * Add an error message to the error container.
  3246. * @access protected
  3247. * @param string $msg
  3248. * @return void
  3249. */
  3250. protected function setError($msg)
  3251. {
  3252. $this->error_count++;
  3253. if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  3254. $lasterror = $this->smtp->getError();
  3255. if (!empty($lasterror['error'])) {
  3256. $msg .= $this->lang('smtp_error') . $lasterror['error'];
  3257. if (!empty($lasterror['detail'])) {
  3258. $msg .= ' Detail: '. $lasterror['detail'];
  3259. }
  3260. if (!empty($lasterror['smtp_code'])) {
  3261. $msg .= ' SMTP code: ' . $lasterror['smtp_code'];
  3262. }
  3263. if (!empty($lasterror['smtp_code_ex'])) {
  3264. $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex'];
  3265. }
  3266. }
  3267. }
  3268. $this->ErrorInfo = $msg;
  3269. }
  3270.  
  3271. /**
  3272. * Return an RFC 822 formatted date.
  3273. * @access public
  3274. * @return string
  3275. * @static
  3276. */
  3277. public static function rfcDate()
  3278. {
  3279. // Set the time zone to whatever the default is to avoid 500 errors
  3280. // Will default to UTC if it's not set properly in php.ini
  3281. date_default_timezone_set(@date_default_timezone_get());
  3282. return date('D, j M Y H:i:s O');
  3283. }
  3284.  
  3285. /**
  3286. * Get the server hostname.
  3287. * Returns 'localhost.localdomain' if unknown.
  3288. * @access protected
  3289. * @return string
  3290. */
  3291. protected function serverHostname()
  3292. {
  3293. $result = 'localhost.localdomain';
  3294. if (!empty($this->Hostname)) {
  3295. $result = $this->Hostname;
  3296. } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) {
  3297. $result = $_SERVER['SERVER_NAME'];
  3298. } elseif (function_exists('gethostname') && gethostname() !== false) {
  3299. $result = gethostname();
  3300. } elseif (php_uname('n') !== false) {
  3301. $result = php_uname('n');
  3302. }
  3303. return $result;
  3304. }
  3305.  
  3306. /**
  3307. * Get an error message in the current language.
  3308. * @access protected
  3309. * @param string $key
  3310. * @return string
  3311. */
  3312. protected function lang($key)
  3313. {
  3314. if (count($this->language) < 1) {
  3315. $this->setLanguage('en'); // set the default language
  3316. }
  3317.  
  3318. if (array_key_exists($key, $this->language)) {
  3319. if ($key == 'smtp_connect_failed') {
  3320. //Include a link to troubleshooting docs on SMTP connection failure
  3321. //this is by far the biggest cause of support questions
  3322. //but it's usually not PHPMailer's fault.
  3323. return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
  3324. }
  3325. return $this->language[$key];
  3326. } else {
  3327. //Return the key as a fallback
  3328. return $key;
  3329. }
  3330. }
  3331.  
  3332. /**
  3333. * Check if an error occurred.
  3334. * @access public
  3335. * @return boolean True if an error did occur.
  3336. */
  3337. public function isError()
  3338. {
  3339. return ($this->error_count > 0);
  3340. }
  3341.  
  3342. /**
  3343. * Ensure consistent line endings in a string.
  3344. * Changes every end of line from CRLF, CR or LF to $this->LE.
  3345. * @access public
  3346. * @param string $str String to fixEOL
  3347. * @return string
  3348. */
  3349. public function fixEOL($str)
  3350. {
  3351. // Normalise to \n
  3352. $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
  3353. // Now convert LE as needed
  3354. if ($this->LE !== "\n") {
  3355. $nstr = str_replace("\n", $this->LE, $nstr);
  3356. }
  3357. return $nstr;
  3358. }
  3359.  
  3360. /**
  3361. * Add a custom header.
  3362. * $name value can be overloaded to contain
  3363. * both header name and value (name:value)
  3364. * @access public
  3365. * @param string $name Custom header name
  3366. * @param string $value Header value
  3367. * @return void
  3368. */
  3369. public function addCustomHeader($name, $value = null)
  3370. {
  3371. if ($value === null) {
  3372. // Value passed in as name:value
  3373. $this->CustomHeader[] = explode(':', $name, 2);
  3374. } else {
  3375. $this->CustomHeader[] = array($name, $value);
  3376. }
  3377. }
  3378.  
  3379. /**
  3380. * Returns all custom headers.
  3381. * @return array
  3382. */
  3383. public function getCustomHeaders()
  3384. {
  3385. return $this->CustomHeader;
  3386. }
  3387.  
  3388. /**
  3389. * Create a message body from an HTML string.
  3390. * Automatically inlines images and creates a plain-text version by converting the HTML,
  3391. * overwriting any existing values in Body and AltBody.
  3392. * Do not source $message content from user input!
  3393. * $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty
  3394. * will look for an image file in $basedir/images/a.png and convert it to inline.
  3395. * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email)
  3396. * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly.
  3397. * @access public
  3398. * @param string $message HTML message string
  3399. * @param string $basedir Absolute path to a base directory to prepend to relative paths to images
  3400. * @param boolean|callable $advanced Whether to use the internal HTML to text converter
  3401. * or your own custom converter @see PHPMailer::html2text()
  3402. * @return string $message The transformed message Body
  3403. */
  3404. public function msgHTML($message, $basedir = '', $advanced = false)
  3405. {
  3406. preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
  3407. if (array_key_exists(2, $images)) {
  3408. if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
  3409. // Ensure $basedir has a trailing /
  3410. $basedir .= '/';
  3411. }
  3412. foreach ($images[2] as $imgindex => $url) {
  3413. // Convert data URIs into embedded images
  3414. if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) {
  3415. $data = substr($url, strpos($url, ','));
  3416. if ($match[2]) {
  3417. $data = base64_decode($data);
  3418. } else {
  3419. $data = rawurldecode($data);
  3420. }
  3421. $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
  3422. if ($this->addStringEmbeddedImage($data, $cid, 'embed' . $imgindex, 'base64', $match[1])) {
  3423. $message = str_replace(
  3424. $images[0][$imgindex],
  3425. $images[1][$imgindex] . '="cid:' . $cid . '"',
  3426. $message
  3427. );
  3428. }
  3429. continue;
  3430. }
  3431. if (
  3432. // Only process relative URLs if a basedir is provided (i.e. no absolute local paths)
  3433. !empty($basedir)
  3434. // Ignore URLs containing parent dir traversal (..)
  3435. && (strpos($url, '..') === false)
  3436. // Do not change urls that are already inline images
  3437. && substr($url, 0, 4) !== 'cid:'
  3438. // Do not change absolute URLs, including anonymous protocol
  3439. && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url)
  3440. ) {
  3441. $filename = basename($url);
  3442. $directory = dirname($url);
  3443. if ($directory == '.') {
  3444. $directory = '';
  3445. }
  3446. $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
  3447. if (strlen($directory) > 1 && substr($directory, -1) != '/') {
  3448. $directory .= '/';
  3449. }
  3450. if ($this->addEmbeddedImage(
  3451. $basedir . $directory . $filename,
  3452. $cid,
  3453. $filename,
  3454. 'base64',
  3455. self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION))
  3456. )
  3457. ) {
  3458. $message = preg_replace(
  3459. '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
  3460. $images[1][$imgindex] . '="cid:' . $cid . '"',
  3461. $message
  3462. );
  3463. }
  3464. }
  3465. }
  3466. }
  3467. $this->isHTML(true);
  3468. // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
  3469. $this->Body = $this->normalizeBreaks($message);
  3470. $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
  3471. if (!$this->alternativeExists()) {
  3472. $this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
  3473. self::CRLF . self::CRLF;
  3474. }
  3475. return $this->Body;
  3476. }
  3477.  
  3478. /**
  3479. * Convert an HTML string into plain text.
  3480. * This is used by msgHTML().
  3481. * Note - older versions of this function used a bundled advanced converter
  3482. * which was been removed for license reasons in #232.
  3483. * Example usage:
  3484. * <code>
  3485. * // Use default conversion
  3486. * $plain = $mail->html2text($html);
  3487. * // Use your own custom converter
  3488. * $plain = $mail->html2text($html, function($html) {
  3489. * $converter = new MyHtml2text($html);
  3490. * return $converter->get_text();
  3491. * });
  3492. * </code>
  3493. * @param string $html The HTML text to convert
  3494. * @param boolean|callable $advanced Any boolean value to use the internal converter,
  3495. * or provide your own callable for custom conversion.
  3496. * @return string
  3497. */
  3498. public function html2text($html, $advanced = false)
  3499. {
  3500. if (is_callable($advanced)) {
  3501. return call_user_func($advanced, $html);
  3502. }
  3503. return html_entity_decode(
  3504. trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
  3505. ENT_QUOTES,
  3506. $this->CharSet
  3507. );
  3508. }
  3509.  
  3510. /**
  3511. * Get the MIME type for a file extension.
  3512. * @param string $ext File extension
  3513. * @access public
  3514. * @return string MIME type of file.
  3515. * @static
  3516. */
  3517. public static function _mime_types($ext = '')
  3518. {
  3519. $mimes = array(
  3520. 'xl' => 'application/excel',
  3521. 'js' => 'application/javascript',
  3522. 'hqx' => 'application/mac-binhex40',
  3523. 'cpt' => 'application/mac-compactpro',
  3524. 'bin' => 'application/macbinary',
  3525. 'doc' => 'application/msword',
  3526. 'word' => 'application/msword',
  3527. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  3528. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  3529. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  3530. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  3531. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  3532. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  3533. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  3534. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  3535. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  3536. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  3537. 'class' => 'application/octet-stream',
  3538. 'dll' => 'application/octet-stream',
  3539. 'dms' => 'application/octet-stream',
  3540. 'exe' => 'application/octet-stream',
  3541. 'lha' => 'application/octet-stream',
  3542. 'lzh' => 'application/octet-stream',
  3543. 'psd' => 'application/octet-stream',
  3544. 'sea' => 'application/octet-stream',
  3545. 'so' => 'application/octet-stream',
  3546. 'oda' => 'application/oda',
  3547. 'pdf' => 'application/pdf',
  3548. 'ai' => 'application/postscript',
  3549. 'eps' => 'application/postscript',
  3550. 'ps' => 'application/postscript',
  3551. 'smi' => 'application/smil',
  3552. 'smil' => 'application/smil',
  3553. 'mif' => 'application/vnd.mif',
  3554. 'xls' => 'application/vnd.ms-excel',
  3555. 'ppt' => 'application/vnd.ms-powerpoint',
  3556. 'wbxml' => 'application/vnd.wap.wbxml',
  3557. 'wmlc' => 'application/vnd.wap.wmlc',
  3558. 'dcr' => 'application/x-director',
  3559. 'dir' => 'application/x-director',
  3560. 'dxr' => 'application/x-director',
  3561. 'dvi' => 'application/x-dvi',
  3562. 'gtar' => 'application/x-gtar',
  3563. 'php3' => 'application/x-httpd-php',
  3564. 'php4' => 'application/x-httpd-php',
  3565. 'php' => 'application/x-httpd-php',
  3566. 'phtml' => 'application/x-httpd-php',
  3567. 'phps' => 'application/x-httpd-php-source',
  3568. 'swf' => 'application/x-shockwave-flash',
  3569. 'sit' => 'application/x-stuffit',
  3570. 'tar' => 'application/x-tar',
  3571. 'tgz' => 'application/x-tar',
  3572. 'xht' => 'application/xhtml+xml',
  3573. 'xhtml' => 'application/xhtml+xml',
  3574. 'zip' => 'application/zip',
  3575. 'mid' => 'audio/midi',
  3576. 'midi' => 'audio/midi',
  3577. 'mp2' => 'audio/mpeg',
  3578. 'mp3' => 'audio/mpeg',
  3579. 'mpga' => 'audio/mpeg',
  3580. 'aif' => 'audio/x-aiff',
  3581. 'aifc' => 'audio/x-aiff',
  3582. 'aiff' => 'audio/x-aiff',
  3583. 'ram' => 'audio/x-pn-realaudio',
  3584. 'rm' => 'audio/x-pn-realaudio',
  3585. 'rpm' => 'audio/x-pn-realaudio-plugin',
  3586. 'ra' => 'audio/x-realaudio',
  3587. 'wav' => 'audio/x-wav',
  3588. 'bmp' => 'image/bmp',
  3589. 'gif' => 'image/gif',
  3590. 'jpeg' => 'image/jpeg',
  3591. 'jpe' => 'image/jpeg',
  3592. 'jpg' => 'image/jpeg',
  3593. 'png' => 'image/png',
  3594. 'tiff' => 'image/tiff',
  3595. 'tif' => 'image/tiff',
  3596. 'eml' => 'message/rfc822',
  3597. 'css' => 'text/css',
  3598. 'html' => 'text/html',
  3599. 'htm' => 'text/html',
  3600. 'shtml' => 'text/html',
  3601. 'log' => 'text/plain',
  3602. 'text' => 'text/plain',
  3603. 'txt' => 'text/plain',
  3604. 'rtx' => 'text/richtext',
  3605. 'rtf' => 'text/rtf',
  3606. 'vcf' => 'text/vcard',
  3607. 'vcard' => 'text/vcard',
  3608. 'xml' => 'text/xml',
  3609. 'xsl' => 'text/xml',
  3610. 'mpeg' => 'video/mpeg',
  3611. 'mpe' => 'video/mpeg',
  3612. 'mpg' => 'video/mpeg',
  3613. 'mov' => 'video/quicktime',
  3614. 'qt' => 'video/quicktime',
  3615. 'rv' => 'video/vnd.rn-realvideo',
  3616. 'avi' => 'video/x-msvideo',
  3617. 'movie' => 'video/x-sgi-movie'
  3618. );
  3619. if (array_key_exists(strtolower($ext), $mimes)) {
  3620. return $mimes[strtolower($ext)];
  3621. }
  3622. return 'application/octet-stream';
  3623. }
  3624.  
  3625. /**
  3626. * Map a file name to a MIME type.
  3627. * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
  3628. * @param string $filename A file name or full path, does not need to exist as a file
  3629. * @return string
  3630. * @static
  3631. */
  3632. public static function filenameToType($filename)
  3633. {
  3634. // In case the path is a URL, strip any query string before getting extension
  3635. $qpos = strpos($filename, '?');
  3636. if (false !== $qpos) {
  3637. $filename = substr($filename, 0, $qpos);
  3638. }
  3639. $pathinfo = self::mb_pathinfo($filename);
  3640. return self::_mime_types($pathinfo['extension']);
  3641. }
  3642.  
  3643. /**
  3644. * Multi-byte-safe pathinfo replacement.
  3645. * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe.
  3646. * Works similarly to the one in PHP >= 5.2.0
  3647. * @link http://www.php.net/manual/en/function.pathinfo.php#107461
  3648. * @param string $path A filename or path, does not need to exist as a file
  3649. * @param integer|string $options Either a PATHINFO_* constant,
  3650. * or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2
  3651. * @return string|array
  3652. * @static
  3653. */
  3654. public static function mb_pathinfo($path, $options = null)
  3655. {
  3656. $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
  3657. $pathinfo = array();
  3658. if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) {
  3659. if (array_key_exists(1, $pathinfo)) {
  3660. $ret['dirname'] = $pathinfo[1];
  3661. }
  3662. if (array_key_exists(2, $pathinfo)) {
  3663. $ret['basename'] = $pathinfo[2];
  3664. }
  3665. if (array_key_exists(5, $pathinfo)) {
  3666. $ret['extension'] = $pathinfo[5];
  3667. }
  3668. if (array_key_exists(3, $pathinfo)) {
  3669. $ret['filename'] = $pathinfo[3];
  3670. }
  3671. }
  3672. switch ($options) {
  3673. case PATHINFO_DIRNAME:
  3674. case 'dirname':
  3675. return $ret['dirname'];
  3676. case PATHINFO_BASENAME:
  3677. case 'basename':
  3678. return $ret['basename'];
  3679. case PATHINFO_EXTENSION:
  3680. case 'extension':
  3681. return $ret['extension'];
  3682. case PATHINFO_FILENAME:
  3683. case 'filename':
  3684. return $ret['filename'];
  3685. default:
  3686. return $ret;
  3687. }
  3688. }
  3689.  
  3690. /**
  3691. * Set or reset instance properties.
  3692. * You should avoid this function - it's more verbose, less efficient, more error-prone and
  3693. * harder to debug than setting properties directly.
  3694. * Usage Example:
  3695. * `$mail->set('SMTPSecure', 'tls');`
  3696. * is the same as:
  3697. * `$mail->SMTPSecure = 'tls';`
  3698. * @access public
  3699. * @param string $name The property name to set
  3700. * @param mixed $value The value to set the property to
  3701. * @return boolean
  3702. * @TODO Should this not be using the __set() magic function?
  3703. */
  3704. public function set($name, $value = '')
  3705. {
  3706. if (property_exists($this, $name)) {
  3707. $this->$name = $value;
  3708. return true;
  3709. } else {
  3710. $this->setError($this->lang('variable_set') . $name);
  3711. return false;
  3712. }
  3713. }
  3714.  
  3715. /**
  3716. * Strip newlines to prevent header injection.
  3717. * @access public
  3718. * @param string $str
  3719. * @return string
  3720. */
  3721. public function secureHeader($str)
  3722. {
  3723. return trim(str_replace(array("\r", "\n"), '', $str));
  3724. }
  3725.  
  3726. /**
  3727. * Normalize line breaks in a string.
  3728. * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
  3729. * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
  3730. * @param string $text
  3731. * @param string $breaktype What kind of line break to use, defaults to CRLF
  3732. * @return string
  3733. * @access public
  3734. * @static
  3735. */
  3736. public static function normalizeBreaks($text, $breaktype = "\r\n")
  3737. {
  3738. return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
  3739. }
  3740.  
  3741. /**
  3742. * Set the public and private key files and password for S/MIME signing.
  3743. * @access public
  3744. * @param string $cert_filename
  3745. * @param string $key_filename
  3746. * @param string $key_pass Password for private key
  3747. * @param string $extracerts_filename Optional path to chain certificate
  3748. */
  3749. public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
  3750. {
  3751. $this->sign_cert_file = $cert_filename;
  3752. $this->sign_key_file = $key_filename;
  3753. $this->sign_key_pass = $key_pass;
  3754. $this->sign_extracerts_file = $extracerts_filename;
  3755. }
  3756.  
  3757. /**
  3758. * Quoted-Printable-encode a DKIM header.
  3759. * @access public
  3760. * @param string $txt
  3761. * @return string
  3762. */
  3763. public function DKIM_QP($txt)
  3764. {
  3765. $line = '';
  3766. for ($i = 0; $i < strlen($txt); $i++) {
  3767. $ord = ord($txt[$i]);
  3768. if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
  3769. $line .= $txt[$i];
  3770. } else {
  3771. $line .= '=' . sprintf('%02X', $ord);
  3772. }
  3773. }
  3774. return $line;
  3775. }
  3776.  
  3777. /**
  3778. * Generate a DKIM signature.
  3779. * @access public
  3780. * @param string $signHeader
  3781. * @throws phpmailerException
  3782. * @return string The DKIM signature value
  3783. */
  3784. public function DKIM_Sign($signHeader)
  3785. {
  3786. if (!defined('PKCS7_TEXT')) {
  3787. if ($this->exceptions) {
  3788. throw new phpmailerException($this->lang('extension_missing') . 'openssl');
  3789. }
  3790. return '';
  3791. }
  3792. $privKeyStr = !empty($this->DKIM_private_string) ? $this->DKIM_private_string : file_get_contents($this->DKIM_private);
  3793. if ('' != $this->DKIM_passphrase) {
  3794. $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  3795. } else {
  3796. $privKey = openssl_pkey_get_private($privKeyStr);
  3797. }
  3798. //Workaround for missing digest algorithms in old PHP & OpenSSL versions
  3799. //@link http://stackoverflow.com/a/11117338/333340
  3800. if (version_compare(PHP_VERSION, '5.3.0') >= 0 and
  3801. in_array('sha256WithRSAEncryption', openssl_get_md_methods(true))) {
  3802. if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
  3803. openssl_pkey_free($privKey);
  3804. return base64_encode($signature);
  3805. }
  3806. } else {
  3807. $pinfo = openssl_pkey_get_details($privKey);
  3808. $hash = hash('sha256', $signHeader);
  3809. //'Magic' constant for SHA256 from RFC3447
  3810. //@link https://tools.ietf.org/html/rfc3447#page-43
  3811. $t = '3031300d060960864801650304020105000420' . $hash;
  3812. $pslen = $pinfo['bits'] / 8 - (strlen($t) / 2 + 3);
  3813. $eb = pack('H*', '0001' . str_repeat('FF', $pslen) . '00' . $t);
  3814.  
  3815. if (openssl_private_encrypt($eb, $signature, $privKey, OPENSSL_NO_PADDING)) {
  3816. openssl_pkey_free($privKey);
  3817. return base64_encode($signature);
  3818. }
  3819. }
  3820. openssl_pkey_free($privKey);
  3821. return '';
  3822. }
  3823.  
  3824. /**
  3825. * Generate a DKIM canonicalization header.
  3826. * @access public
  3827. * @param string $signHeader Header
  3828. * @return string
  3829. */
  3830. public function DKIM_HeaderC($signHeader)
  3831. {
  3832. $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader);
  3833. $lines = explode("\r\n", $signHeader);
  3834. foreach ($lines as $key => $line) {
  3835. list($heading, $value) = explode(':', $line, 2);
  3836. $heading = strtolower($heading);
  3837. $value = preg_replace('/\s{2,}/', ' ', $value); // Compress useless spaces
  3838. $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value
  3839. }
  3840. $signHeader = implode("\r\n", $lines);
  3841. return $signHeader;
  3842. }
  3843.  
  3844. /**
  3845. * Generate a DKIM canonicalization body.
  3846. * @access public
  3847. * @param string $body Message Body
  3848. * @return string
  3849. */
  3850. public function DKIM_BodyC($body)
  3851. {
  3852. if ($body == '') {
  3853. return "\r\n";
  3854. }
  3855. // stabilize line endings
  3856. $body = str_replace("\r\n", "\n", $body);
  3857. $body = str_replace("\n", "\r\n", $body);
  3858. // END stabilize line endings
  3859. while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
  3860. $body = substr($body, 0, strlen($body) - 2);
  3861. }
  3862. return $body;
  3863. }
  3864.  
  3865. /**
  3866. * Create the DKIM header and body in a new message header.
  3867. * @access public
  3868. * @param string $headers_line Header lines
  3869. * @param string $subject Subject
  3870. * @param string $body Body
  3871. * @return string
  3872. */
  3873. public function DKIM_Add($headers_line, $subject, $body)
  3874. {
  3875. $DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms
  3876. $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  3877. $DKIMquery = 'dns/txt'; // Query method
  3878. $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  3879. $subject_header = "Subject: $subject";
  3880. $headers = explode($this->LE, $headers_line);
  3881. $from_header = '';
  3882. $to_header = '';
  3883. $date_header = '';
  3884. $current = '';
  3885. foreach ($headers as $header) {
  3886. if (strpos($header, 'From:') === 0) {
  3887. $from_header = $header;
  3888. $current = 'from_header';
  3889. } elseif (strpos($header, 'To:') === 0) {
  3890. $to_header = $header;
  3891. $current = 'to_header';
  3892. } elseif (strpos($header, 'Date:') === 0) {
  3893. $date_header = $header;
  3894. $current = 'date_header';
  3895. } else {
  3896. if (!empty($$current) && strpos($header, ' =?') === 0) {
  3897. $$current .= $header;
  3898. } else {
  3899. $current = '';
  3900. }
  3901. }
  3902. }
  3903. $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  3904. $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  3905. $date = str_replace('|', '=7C', $this->DKIM_QP($date_header));
  3906. $subject = str_replace(
  3907. '|',
  3908. '=7C',
  3909. $this->DKIM_QP($subject_header)
  3910. ); // Copied header fields (dkim-quoted-printable)
  3911. $body = $this->DKIM_BodyC($body);
  3912. $DKIMlen = strlen($body); // Length of body
  3913. $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body
  3914. if ('' == $this->DKIM_identity) {
  3915. $ident = '';
  3916. } else {
  3917. $ident = ' i=' . $this->DKIM_identity . ';';
  3918. }
  3919. $dkimhdrs = 'DKIM-Signature: v=1; a=' .
  3920. $DKIMsignatureType . '; q=' .
  3921. $DKIMquery . '; l=' .
  3922. $DKIMlen . '; s=' .
  3923. $this->DKIM_selector .
  3924. ";\r\n" .
  3925. "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
  3926. "\th=From:To:Date:Subject;\r\n" .
  3927. "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
  3928. "\tz=$from\r\n" .
  3929. "\t|$to\r\n" .
  3930. "\t|$date\r\n" .
  3931. "\t|$subject;\r\n" .
  3932. "\tbh=" . $DKIMb64 . ";\r\n" .
  3933. "\tb=";
  3934. $toSign = $this->DKIM_HeaderC(
  3935. $from_header . "\r\n" .
  3936. $to_header . "\r\n" .
  3937. $date_header . "\r\n" .
  3938. $subject_header . "\r\n" .
  3939. $dkimhdrs
  3940. );
  3941. $signed = $this->DKIM_Sign($toSign);
  3942. return $dkimhdrs . $signed . "\r\n";
  3943. }
  3944.  
  3945. /**
  3946. * Detect if a string contains a line longer than the maximum line length allowed.
  3947. * @param string $str
  3948. * @return boolean
  3949. * @static
  3950. */
  3951. public static function hasLineLongerThanMax($str)
  3952. {
  3953. //+2 to include CRLF line break for a 1000 total
  3954. return (boolean)preg_match('/^(.{'.(self::MAX_LINE_LENGTH + 2).',})/m', $str);
  3955. }
  3956.  
  3957. /**
  3958. * Allows for public read access to 'to' property.
  3959. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  3960. * @access public
  3961. * @return array
  3962. */
  3963. public function getToAddresses()
  3964. {
  3965. return $this->to;
  3966. }
  3967.  
  3968. /**
  3969. * Allows for public read access to 'cc' property.
  3970. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  3971. * @access public
  3972. * @return array
  3973. */
  3974. public function getCcAddresses()
  3975. {
  3976. return $this->cc;
  3977. }
  3978.  
  3979. /**
  3980. * Allows for public read access to 'bcc' property.
  3981. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  3982. * @access public
  3983. * @return array
  3984. */
  3985. public function getBccAddresses()
  3986. {
  3987. return $this->bcc;
  3988. }
  3989.  
  3990. /**
  3991. * Allows for public read access to 'ReplyTo' property.
  3992. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  3993. * @access public
  3994. * @return array
  3995. */
  3996. public function getReplyToAddresses()
  3997. {
  3998. return $this->ReplyTo;
  3999. }
  4000.  
  4001. /**
  4002. * Allows for public read access to 'all_recipients' property.
  4003. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  4004. * @access public
  4005. * @return array
  4006. */
  4007. public function getAllRecipientAddresses()
  4008. {
  4009. return $this->all_recipients;
  4010. }
  4011.  
  4012. /**
  4013. * Perform a callback.
  4014. * @param boolean $isSent
  4015. * @param array $to
  4016. * @param array $cc
  4017. * @param array $bcc
  4018. * @param string $subject
  4019. * @param string $body
  4020. * @param string $from
  4021. */
  4022. protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from)
  4023. {
  4024. if (!empty($this->action_function) && is_callable($this->action_function)) {
  4025. $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
  4026. call_user_func_array($this->action_function, $params);
  4027. }
  4028. }
  4029. }
  4030.  
  4031. /**
  4032. * PHPMailer exception handler
  4033. * @package PHPMailer
  4034. */
  4035. class phpmailerException extends Exception
  4036. {
  4037. /**
  4038. * Prettify error message output
  4039. * @return string
  4040. */
  4041. public function errorMessage()
  4042. {
  4043. $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  4044. return $errorMsg;
  4045. }
  4046. }
Add Comment
Please, Sign In to add comment