Guest User

Untitled

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