Guest User

Untitled

a guest
Mar 5th, 2017
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 180.05 KB | None | 0 0
  1. <?php
  2. /**
  3. * PHPMailer - PHP email creation and transport class.
  4. * PHP Version 5
  5. * @package PHPMailer
  6. * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
  7. * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  8. * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  9. * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  10. * @author Brent R. Matzelle (original founder)
  11. * @copyright 2012 - 2014 Marcus Bointon
  12. * @copyright 2010 - 2012 Jim Jagielski
  13. * @copyright 2004 - 2009 Andy Prevost
  14. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  15. * @note This program is distributed in the hope that it will be useful - WITHOUT
  16. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  17. * FITNESS FOR A PARTICULAR PURPOSE.
  18. */
  19.  
  20. /**
  21. * PHPMailer - PHP email creation and transport class.
  22. * @package PHPMailer
  23. * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  24. * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  25. * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  26. * @author Brent R. Matzelle (original founder)
  27. */
  28.  
  29. if (! defined ( 'DATALIFEENGINE' )) {
  30. die ( "Hacking attempt!" );
  31. }
  32.  
  33. class PHPMailer
  34. {
  35. /**
  36. * The PHPMailer Version number.
  37. * @var string
  38. */
  39. public $Version = '5.2.14';
  40.  
  41. /**
  42. * Email priority.
  43. * Options: null (default), 1 = High, 3 = Normal, 5 = low.
  44. * When null, the header is not set at all.
  45. * @var integer
  46. */
  47. public $Priority = null;
  48.  
  49. /**
  50. * The character set of the message.
  51. * @var string
  52. */
  53. public $CharSet = 'iso-8859-1';
  54.  
  55. /**
  56. * The MIME Content-type of the message.
  57. * @var string
  58. */
  59. public $ContentType = 'text/plain';
  60.  
  61. /**
  62. * The message encoding.
  63. * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
  64. * @var string
  65. */
  66. public $Encoding = '8bit';
  67.  
  68. /**
  69. * Holds the most recent mailer error message.
  70. * @var string
  71. */
  72. public $ErrorInfo = '';
  73.  
  74. /**
  75. * The From email address for the message.
  76. * @var string
  77. */
  78. public $From = 'root@localhost';
  79.  
  80. /**
  81. * The From name of the message.
  82. * @var string
  83. */
  84. public $FromName = 'Root User';
  85.  
  86. /**
  87. * The Sender email (Return-Path) of the message.
  88. * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  89. * @var string
  90. */
  91. public $Sender = '';
  92.  
  93. /**
  94. * The Return-Path of the message.
  95. * If empty, it will be set to either From or Sender.
  96. * @var string
  97. * @deprecated Email senders should never set a return-path header;
  98. * it's the receiver's job (RFC5321 section 4.4), so this no longer does anything.
  99. * @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference
  100. */
  101. public $ReturnPath = '';
  102.  
  103. /**
  104. * The Subject of the message.
  105. * @var string
  106. */
  107. public $Subject = '';
  108.  
  109. /**
  110. * An HTML or plain text message body.
  111. * If HTML then call isHTML(true).
  112. * @var string
  113. */
  114. public $Body = '';
  115.  
  116. /**
  117. * The plain-text message body.
  118. * This body can be read by mail clients that do not have HTML email
  119. * capability such as mutt & Eudora.
  120. * Clients that can read HTML will view the normal Body.
  121. * @var string
  122. */
  123. public $AltBody = '';
  124.  
  125. /**
  126. * An iCal message part body.
  127. * Only supported in simple alt or alt_inline message types
  128. * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator
  129. * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
  130. * @link http://kigkonsult.se/iCalcreator/
  131. * @var string
  132. */
  133. public $Ical = '';
  134.  
  135. /**
  136. * The complete compiled MIME message body.
  137. * @access protected
  138. * @var string
  139. */
  140. protected $MIMEBody = '';
  141.  
  142. /**
  143. * The complete compiled MIME message headers.
  144. * @var string
  145. * @access protected
  146. */
  147. protected $MIMEHeader = '';
  148.  
  149. /**
  150. * Extra headers that createHeader() doesn't fold in.
  151. * @var string
  152. * @access protected
  153. */
  154. protected $mailHeader = '';
  155.  
  156. /**
  157. * Word-wrap the message body to this number of chars.
  158. * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
  159. * @var integer
  160. */
  161. public $WordWrap = 0;
  162.  
  163. /**
  164. * Which method to use to send mail.
  165. * Options: "mail", "sendmail", or "smtp".
  166. * @var string
  167. */
  168. public $Mailer = 'mail';
  169.  
  170. /**
  171. * The path to the sendmail program.
  172. * @var string
  173. */
  174. public $Sendmail = '/usr/sbin/sendmail';
  175.  
  176. /**
  177. * Whether mail() uses a fully sendmail-compatible MTA.
  178. * One which supports sendmail's "-oi -f" options.
  179. * @var boolean
  180. */
  181. public $UseSendmailOptions = true;
  182.  
  183. /**
  184. * Path to PHPMailer plugins.
  185. * Useful if the SMTP class is not in the PHP include path.
  186. * @var string
  187. * @deprecated Should not be needed now there is an autoloader.
  188. */
  189. public $PluginDir = '';
  190.  
  191. /**
  192. * The email address that a reading confirmation should be sent to, also known as read receipt.
  193. * @var string
  194. */
  195. public $ConfirmReadingTo = '';
  196.  
  197. /**
  198. * The hostname to use in the Message-ID header and as default HELO string.
  199. * If empty, PHPMailer attempts to find one with, in order,
  200. * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value
  201. * 'localhost.localdomain'.
  202. * @var string
  203. */
  204. public $Hostname = '';
  205.  
  206. /**
  207. * An ID to be used in the Message-ID header.
  208. * If empty, a unique id will be generated.
  209. * @var string
  210. */
  211. public $MessageID = '';
  212.  
  213. /**
  214. * The message Date to be used in the Date header.
  215. * If empty, the current date will be added.
  216. * @var string
  217. */
  218. public $MessageDate = '';
  219.  
  220. /**
  221. * SMTP hosts.
  222. * Either a single hostname or multiple semicolon-delimited hostnames.
  223. * You can also specify a different port
  224. * for each host by using this format: [hostname:port]
  225. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  226. * You can also specify encryption type, for example:
  227. * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
  228. * Hosts will be tried in order.
  229. * @var string
  230. */
  231. public $Host = 'localhost';
  232.  
  233. /**
  234. * The default SMTP server port.
  235. * @var integer
  236. * @TODO Why is this needed when the SMTP class takes care of it?
  237. */
  238. public $Port = 25;
  239.  
  240. /**
  241. * The SMTP HELO of the message.
  242. * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find
  243. * one with the same method described above for $Hostname.
  244. * @var string
  245. * @see PHPMailer::$Hostname
  246. */
  247. public $Helo = '';
  248.  
  249. /**
  250. * What kind of encryption to use on the SMTP connection.
  251. * Options: '', 'ssl' or 'tls'
  252. * @var string
  253. */
  254. public $SMTPSecure = '';
  255.  
  256. /**
  257. * Whether to enable TLS encryption automatically if a server supports it,
  258. * even if `SMTPSecure` is not set to 'tls'.
  259. * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
  260. * @var boolean
  261. */
  262. public $SMTPAutoTLS = true;
  263.  
  264. /**
  265. * Whether to use SMTP authentication.
  266. * Uses the Username and Password properties.
  267. * @var boolean
  268. * @see PHPMailer::$Username
  269. * @see PHPMailer::$Password
  270. */
  271. public $SMTPAuth = false;
  272.  
  273. /**
  274. * Options array passed to stream_context_create when connecting via SMTP.
  275. * @var array
  276. */
  277. public $SMTPOptions = array();
  278.  
  279. /**
  280. * SMTP username.
  281. * @var string
  282. */
  283. public $Username = '';
  284.  
  285. /**
  286. * SMTP password.
  287. * @var string
  288. */
  289. public $Password = '';
  290.  
  291. /**
  292. * SMTP auth type.
  293. * Options are LOGIN (default), PLAIN, NTLM, CRAM-MD5
  294. * @var string
  295. */
  296. public $AuthType = '';
  297.  
  298. /**
  299. * SMTP realm.
  300. * Used for NTLM auth
  301. * @var string
  302. */
  303. public $Realm = '';
  304.  
  305. /**
  306. * SMTP workstation.
  307. * Used for NTLM auth
  308. * @var string
  309. */
  310. public $Workstation = '';
  311.  
  312. /**
  313. * The SMTP server timeout in seconds.
  314. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
  315. * @var integer
  316. */
  317. public $Timeout = 300;
  318.  
  319. /**
  320. * SMTP class debug output mode.
  321. * Debug output level.
  322. * Options:
  323. * * `0` No output
  324. * * `1` Commands
  325. * * `2` Data and commands
  326. * * `3` As 2 plus connection status
  327. * * `4` Low-level data output
  328. * @var integer
  329. * @see SMTP::$do_debug
  330. */
  331. public $SMTPDebug = 0;
  332.  
  333. /**
  334. * How to handle debug output.
  335. * Options:
  336. * * `echo` Output plain-text as-is, appropriate for CLI
  337. * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
  338. * * `error_log` Output to error log as configured in php.ini
  339. *
  340. * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
  341. * <code>
  342. * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
  343. * </code>
  344. * @var string|callable
  345. * @see SMTP::$Debugoutput
  346. */
  347. public $Debugoutput = 'echo';
  348.  
  349. /**
  350. * Whether to keep SMTP connection open after each message.
  351. * If this is set to true then to close the connection
  352. * requires an explicit call to smtpClose().
  353. * @var boolean
  354. */
  355. public $SMTPKeepAlive = false;
  356.  
  357. /**
  358. * Whether to split multiple to addresses into multiple messages
  359. * or send them all in one message.
  360. * @var boolean
  361. */
  362. public $SingleTo = false;
  363.  
  364. /**
  365. * Storage for addresses when SingleTo is enabled.
  366. * @var array
  367. * @TODO This should really not be public
  368. */
  369. public $SingleToArray = array();
  370.  
  371. /**
  372. * Whether to generate VERP addresses on send.
  373. * Only applicable when sending via SMTP.
  374. * @link https://en.wikipedia.org/wiki/Variable_envelope_return_path
  375. * @link http://www.postfix.org/VERP_README.html Postfix VERP info
  376. * @var boolean
  377. */
  378. public $do_verp = false;
  379.  
  380. /**
  381. * Whether to allow sending messages with an empty body.
  382. * @var boolean
  383. */
  384. public $AllowEmpty = false;
  385.  
  386. /**
  387. * The default line ending.
  388. * @note The default remains "\n". We force CRLF where we know
  389. * it must be used via self::CRLF.
  390. * @var string
  391. */
  392. public $LE = "\n";
  393.  
  394. /**
  395. * DKIM selector.
  396. * @var string
  397. */
  398. public $DKIM_selector = '';
  399.  
  400. /**
  401. * DKIM Identity.
  402. * Usually the email address used as the source of the email
  403. * @var string
  404. */
  405. public $DKIM_identity = '';
  406.  
  407. /**
  408. * DKIM passphrase.
  409. * Used if your key is encrypted.
  410. * @var string
  411. */
  412. public $DKIM_passphrase = '';
  413.  
  414. /**
  415. * DKIM signing domain name.
  416. * @example 'example.com'
  417. * @var string
  418. */
  419. public $DKIM_domain = '';
  420.  
  421. /**
  422. * DKIM private key file path.
  423. * @var string
  424. */
  425. public $DKIM_private = '';
  426.  
  427. /**
  428. * Callback Action function name.
  429. *
  430. * The function that handles the result of the send email action.
  431. * It is called out by send() for each email sent.
  432. *
  433. * Value can be any php callable: http://www.php.net/is_callable
  434. *
  435. * Parameters:
  436. * boolean $result result of the send action
  437. * string $to email address of the recipient
  438. * string $cc cc email addresses
  439. * string $bcc bcc email addresses
  440. * string $subject the subject
  441. * string $body the email body
  442. * string $from email address of sender
  443. * @var string
  444. */
  445. public $action_function = '';
  446.  
  447. /**
  448. * What to put in the X-Mailer header.
  449. * Options: An empty string for PHPMailer default, whitespace for none, or a string to use
  450. * @var string
  451. */
  452. public $XMailer = '';
  453.  
  454. /**
  455. * An instance of the SMTP sender class.
  456. * @var SMTP
  457. * @access protected
  458. */
  459. protected $smtp = null;
  460.  
  461. /**
  462. * The array of 'to' names and addresses.
  463. * @var array
  464. * @access protected
  465. */
  466. protected $to = array();
  467.  
  468. /**
  469. * The array of 'cc' names and addresses.
  470. * @var array
  471. * @access protected
  472. */
  473. protected $cc = array();
  474.  
  475. /**
  476. * The array of 'bcc' names and addresses.
  477. * @var array
  478. * @access protected
  479. */
  480. protected $bcc = array();
  481.  
  482. /**
  483. * The array of reply-to names and addresses.
  484. * @var array
  485. * @access protected
  486. */
  487. protected $ReplyTo = array();
  488.  
  489. /**
  490. * An array of all kinds of addresses.
  491. * Includes all of $to, $cc, $bcc
  492. * @var array
  493. * @access protected
  494. * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc
  495. */
  496. protected $all_recipients = array();
  497.  
  498. /**
  499. * An array of names and addresses queued for validation.
  500. * In send(), valid and non duplicate entries are moved to $all_recipients
  501. * and one of $to, $cc, or $bcc.
  502. * This array is used only for addresses with IDN.
  503. * @var array
  504. * @access protected
  505. * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc
  506. * @see PHPMailer::$all_recipients
  507. */
  508. protected $RecipientsQueue = array();
  509.  
  510. /**
  511. * An array of reply-to names and addresses queued for validation.
  512. * In send(), valid and non duplicate entries are moved to $ReplyTo.
  513. * This array is used only for addresses with IDN.
  514. * @var array
  515. * @access protected
  516. * @see PHPMailer::$ReplyTo
  517. */
  518. protected $ReplyToQueue = array();
  519.  
  520. /**
  521. * The array of attachments.
  522. * @var array
  523. * @access protected
  524. */
  525. protected $attachment = array();
  526.  
  527. /**
  528. * The array of custom headers.
  529. * @var array
  530. * @access protected
  531. */
  532. protected $CustomHeader = array();
  533.  
  534. /**
  535. * The most recent Message-ID (including angular brackets).
  536. * @var string
  537. * @access protected
  538. */
  539. protected $lastMessageID = '';
  540.  
  541. /**
  542. * The message's MIME type.
  543. * @var string
  544. * @access protected
  545. */
  546. protected $message_type = '';
  547.  
  548. /**
  549. * The array of MIME boundary strings.
  550. * @var array
  551. * @access protected
  552. */
  553. protected $boundary = array();
  554.  
  555. /**
  556. * The array of available languages.
  557. * @var array
  558. * @access protected
  559. */
  560. protected $language = array();
  561.  
  562. /**
  563. * The number of errors encountered.
  564. * @var integer
  565. * @access protected
  566. */
  567. protected $error_count = 0;
  568.  
  569. /**
  570. * The S/MIME certificate file path.
  571. * @var string
  572. * @access protected
  573. */
  574. protected $sign_cert_file = '';
  575.  
  576. /**
  577. * The S/MIME key file path.
  578. * @var string
  579. * @access protected
  580. */
  581. protected $sign_key_file = '';
  582.  
  583. /**
  584. * The optional S/MIME extra certificates ("CA Chain") file path.
  585. * @var string
  586. * @access protected
  587. */
  588. protected $sign_extracerts_file = '';
  589.  
  590. /**
  591. * The S/MIME password for the key.
  592. * Used only if the key is encrypted.
  593. * @var string
  594. * @access protected
  595. */
  596. protected $sign_key_pass = '';
  597.  
  598. /**
  599. * Whether to throw exceptions for errors.
  600. * @var boolean
  601. * @access protected
  602. */
  603. protected $exceptions = false;
  604.  
  605. /**
  606. * Unique ID used for message ID and boundaries.
  607. * @var string
  608. * @access protected
  609. */
  610. protected $uniqueid = '';
  611.  
  612. /**
  613. * Error severity: message only, continue processing.
  614. */
  615. const STOP_MESSAGE = 0;
  616.  
  617. /**
  618. * Error severity: message, likely ok to continue processing.
  619. */
  620. const STOP_CONTINUE = 1;
  621.  
  622. /**
  623. * Error severity: message, plus full stop, critical error reached.
  624. */
  625. const STOP_CRITICAL = 2;
  626.  
  627. /**
  628. * SMTP RFC standard line ending.
  629. */
  630. const CRLF = "\r\n";
  631.  
  632. /**
  633. * The maximum line length allowed by RFC 2822 section 2.1.1
  634. * @var integer
  635. */
  636. const MAX_LINE_LENGTH = 998;
  637.  
  638. /**
  639. * Constructor.
  640. * @param boolean $exceptions Should we throw external exceptions?
  641. */
  642. public function __construct($exceptions = false)
  643. {
  644. $this->exceptions = (boolean)$exceptions;
  645. }
  646.  
  647. /**
  648. * Destructor.
  649. */
  650. public function __destruct()
  651. {
  652. //Close any open SMTP connection nicely
  653. if ($this->Mailer == 'smtp') {
  654. $this->smtpClose();
  655. }
  656. }
  657.  
  658. /**
  659. * Call mail() in a safe_mode-aware fashion.
  660. * Also, unless sendmail_path points to sendmail (or something that
  661. * claims to be sendmail), don't pass params (not a perfect fix,
  662. * but it will do)
  663. * @param string $to To
  664. * @param string $subject Subject
  665. * @param string $body Message Body
  666. * @param string $header Additional Header(s)
  667. * @param string $params Params
  668. * @access private
  669. * @return boolean
  670. */
  671. private function mailPassthru($to, $subject, $body, $header, $params)
  672. {
  673. //Check overloading of mail function to avoid double-encoding
  674. if (ini_get('mbstring.func_overload') & 1) {
  675. $subject = $this->secureHeader($subject);
  676. } else {
  677. $subject = $this->encodeHeader($this->secureHeader($subject));
  678. }
  679. if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {
  680. $result = @mail($to, $subject, $body, $header);
  681. } else {
  682. $result = @mail($to, $subject, $body, $header, $params);
  683. }
  684. return $result;
  685. }
  686.  
  687. /**
  688. * Output debugging info via user-defined method.
  689. * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
  690. * @see PHPMailer::$Debugoutput
  691. * @see PHPMailer::$SMTPDebug
  692. * @param string $str
  693. */
  694. protected function edebug($str)
  695. {
  696. if ($this->SMTPDebug <= 0) {
  697. return;
  698. }
  699. //Avoid clash with built-in function names
  700. if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
  701. call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
  702. return;
  703. }
  704. switch ($this->Debugoutput) {
  705. case 'error_log':
  706. //Don't output, just log
  707. error_log($str);
  708. break;
  709. case 'html':
  710. //Cleans up output a bit for a better looking, HTML-safe output
  711. echo htmlentities(
  712. preg_replace('/[\r\n]+/', '', $str),
  713. ENT_QUOTES,
  714. 'UTF-8'
  715. )
  716. . "<br>\n";
  717. break;
  718. case 'echo':
  719. default:
  720. //Normalize line breaks
  721. $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
  722. echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
  723. "\n",
  724. "\n \t ",
  725. trim($str)
  726. ) . "\n";
  727. }
  728. }
  729.  
  730. /**
  731. * Sets message type to HTML or plain.
  732. * @param boolean $isHtml True for HTML mode.
  733. * @return void
  734. */
  735. public function isHTML($isHtml = true)
  736. {
  737. if ($isHtml) {
  738. $this->ContentType = 'text/html';
  739. } else {
  740. $this->ContentType = 'text/plain';
  741. }
  742. }
  743.  
  744. /**
  745. * Send messages using SMTP.
  746. * @return void
  747. */
  748. public function isSMTP()
  749. {
  750. $this->Mailer = 'smtp';
  751. }
  752.  
  753. /**
  754. * Send messages using PHP's mail() function.
  755. * @return void
  756. */
  757. public function isMail()
  758. {
  759. $this->Mailer = 'mail';
  760. }
  761.  
  762. /**
  763. * Send messages using $Sendmail.
  764. * @return void
  765. */
  766. public function isSendmail()
  767. {
  768. $ini_sendmail_path = ini_get('sendmail_path');
  769.  
  770. if (!stristr($ini_sendmail_path, 'sendmail')) {
  771. $this->Sendmail = '/usr/sbin/sendmail';
  772. } else {
  773. $this->Sendmail = $ini_sendmail_path;
  774. }
  775. $this->Mailer = 'sendmail';
  776. }
  777.  
  778. /**
  779. * Send messages using qmail.
  780. * @return void
  781. */
  782. public function isQmail()
  783. {
  784. $ini_sendmail_path = ini_get('sendmail_path');
  785.  
  786. if (!stristr($ini_sendmail_path, 'qmail')) {
  787. $this->Sendmail = '/var/qmail/bin/qmail-inject';
  788. } else {
  789. $this->Sendmail = $ini_sendmail_path;
  790. }
  791. $this->Mailer = 'qmail';
  792. }
  793.  
  794. /**
  795. * Add a "To" address.
  796. * @param string $address The email address to send to
  797. * @param string $name
  798. * @return boolean true on success, false if address already used or invalid in some way
  799. */
  800. public function addAddress($address, $name = '')
  801. {
  802. return $this->addOrEnqueueAnAddress('to', $address, $name);
  803. }
  804.  
  805. /**
  806. * Add a "CC" address.
  807. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
  808. * @param string $address The email address to send to
  809. * @param string $name
  810. * @return boolean true on success, false if address already used or invalid in some way
  811. */
  812. public function addCC($address, $name = '')
  813. {
  814. return $this->addOrEnqueueAnAddress('cc', $address, $name);
  815. }
  816.  
  817. /**
  818. * Add a "BCC" address.
  819. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
  820. * @param string $address The email address to send to
  821. * @param string $name
  822. * @return boolean true on success, false if address already used or invalid in some way
  823. */
  824. public function addBCC($address, $name = '')
  825. {
  826. return $this->addOrEnqueueAnAddress('bcc', $address, $name);
  827. }
  828.  
  829. /**
  830. * Add a "Reply-To" address.
  831. * @param string $address The email address to reply to
  832. * @param string $name
  833. * @return boolean true on success, false if address already used or invalid in some way
  834. */
  835. public function addReplyTo($address, $name = '')
  836. {
  837. return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
  838. }
  839.  
  840. /**
  841. * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer
  842. * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still
  843. * be modified after calling this function), addition of such addresses is delayed until send().
  844. * Addresses that have been added already return false, but do not throw exceptions.
  845. * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
  846. * @param string $address The email address to send, resp. to reply to
  847. * @param string $name
  848. * @throws phpmailerException
  849. * @return boolean true on success, false if address already used or invalid in some way
  850. * @access protected
  851. */
  852. protected function addOrEnqueueAnAddress($kind, $address, $name)
  853. {
  854. $address = trim($address);
  855. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  856. if (($pos = strrpos($address, '@')) === false) {
  857. // At-sign is misssing.
  858. $error_message = $this->lang('invalid_address') . $address;
  859. $this->setError($error_message);
  860. $this->edebug($error_message);
  861. if ($this->exceptions) {
  862. throw new phpmailerException($error_message);
  863. }
  864. return false;
  865. }
  866. $params = array($kind, $address, $name);
  867. // Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
  868. if ($this->has8bitChars(substr($address, ++$pos)) and $this->idnSupported()) {
  869. if ($kind != 'Reply-To') {
  870. if (!array_key_exists($address, $this->RecipientsQueue)) {
  871. $this->RecipientsQueue[$address] = $params;
  872. return true;
  873. }
  874. } else {
  875. if (!array_key_exists($address, $this->ReplyToQueue)) {
  876. $this->ReplyToQueue[$address] = $params;
  877. return true;
  878. }
  879. }
  880. return false;
  881. }
  882. // Immediately add standard addresses without IDN.
  883. return call_user_func_array(array($this, 'addAnAddress'), $params);
  884. }
  885.  
  886. /**
  887. * Add an address to one of the recipient arrays or to the ReplyTo array.
  888. * Addresses that have been added already return false, but do not throw exceptions.
  889. * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
  890. * @param string $address The email address to send, resp. to reply to
  891. * @param string $name
  892. * @throws phpmailerException
  893. * @return boolean true on success, false if address already used or invalid in some way
  894. * @access protected
  895. */
  896. protected function addAnAddress($kind, $address, $name = '')
  897. {
  898. if (!in_array($kind, array('to', 'cc', 'bcc', 'Reply-To'))) {
  899. $error_message = $this->lang('Invalid recipient kind: ') . $kind;
  900. $this->setError($error_message);
  901. $this->edebug($error_message);
  902. if ($this->exceptions) {
  903. throw new phpmailerException($error_message);
  904. }
  905. return false;
  906. }
  907. if (!$this->validateAddress($address)) {
  908. $error_message = $this->lang('invalid_address') . $address;
  909. $this->setError($error_message);
  910. $this->edebug($error_message);
  911. if ($this->exceptions) {
  912. throw new phpmailerException($error_message);
  913. }
  914. return false;
  915. }
  916. if ($kind != 'Reply-To') {
  917. if (!array_key_exists(strtolower($address), $this->all_recipients)) {
  918. array_push($this->$kind, array($address, $name));
  919. $this->all_recipients[strtolower($address)] = true;
  920. return true;
  921. }
  922. } else {
  923. if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  924. $this->ReplyTo[strtolower($address)] = array($address, $name);
  925. return true;
  926. }
  927. }
  928. return false;
  929. }
  930.  
  931. /**
  932. * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
  933. * of the form "display name <address>" into an array of name/address pairs.
  934. * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
  935. * Note that quotes in the name part are removed.
  936. * @param string $addrstr The address list string
  937. * @param bool $useimap Whether to use the IMAP extension to parse the list
  938. * @return array
  939. * @link http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
  940. */
  941. public function parseAddresses($addrstr, $useimap = true)
  942. {
  943. $addresses = array();
  944. if ($useimap and function_exists('imap_rfc822_parse_adrlist')) {
  945. //Use this built-in parser if it's available
  946. $list = imap_rfc822_parse_adrlist($addrstr, '');
  947. foreach ($list as $address) {
  948. if ($address->host != '.SYNTAX-ERROR.') {
  949. if ($this->validateAddress($address->mailbox . '@' . $address->host)) {
  950. $addresses[] = array(
  951. 'name' => (property_exists($address, 'personal') ? $address->personal : ''),
  952. 'address' => $address->mailbox . '@' . $address->host
  953. );
  954. }
  955. }
  956. }
  957. } else {
  958. //Use this simpler parser
  959. $list = explode(',', $addrstr);
  960. foreach ($list as $address) {
  961. $address = trim($address);
  962. //Is there a separate name part?
  963. if (strpos($address, '<') === false) {
  964. //No separate name, just use the whole thing
  965. if ($this->validateAddress($address)) {
  966. $addresses[] = array(
  967. 'name' => '',
  968. 'address' => $address
  969. );
  970. }
  971. } else {
  972. list($name, $email) = explode('<', $address);
  973. $email = trim(str_replace('>', '', $email));
  974. if ($this->validateAddress($email)) {
  975. $addresses[] = array(
  976. 'name' => trim(str_replace(array('"', "'"), '', $name)),
  977. 'address' => $email
  978. );
  979. }
  980. }
  981. }
  982. }
  983. return $addresses;
  984. }
  985.  
  986. /**
  987. * Set the From and FromName properties.
  988. * @param string $address
  989. * @param string $name
  990. * @param boolean $auto Whether to also set the Sender address, defaults to true
  991. * @throws phpmailerException
  992. * @return boolean
  993. */
  994. public function setFrom($address, $name = '', $auto = true)
  995. {
  996. $address = trim($address);
  997. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  998. // Don't validate now addresses with IDN. Will be done in send().
  999. if (($pos = strrpos($address, '@')) === false or
  1000. (!$this->has8bitChars(substr($address, ++$pos)) or !$this->idnSupported()) and
  1001. !$this->validateAddress($address)) {
  1002. $error_message = $this->lang('invalid_address') . $address;
  1003. $this->setError($error_message);
  1004. $this->edebug($error_message);
  1005. if ($this->exceptions) {
  1006. throw new phpmailerException($error_message);
  1007. }
  1008. return false;
  1009. }
  1010. $this->From = $address;
  1011. $this->FromName = $name;
  1012. if ($auto) {
  1013. if (empty($this->Sender)) {
  1014. $this->Sender = $address;
  1015. }
  1016. }
  1017. return true;
  1018. }
  1019.  
  1020. /**
  1021. * Return the Message-ID header of the last email.
  1022. * Technically this is the value from the last time the headers were created,
  1023. * but it's also the message ID of the last sent message except in
  1024. * pathological cases.
  1025. * @return string
  1026. */
  1027. public function getLastMessageID()
  1028. {
  1029. return $this->lastMessageID;
  1030. }
  1031.  
  1032. /**
  1033. * Check that a string looks like an email address.
  1034. * @param string $address The email address to check
  1035. * @param string $patternselect A selector for the validation pattern to use :
  1036. * * `auto` Pick best pattern automatically;
  1037. * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
  1038. * * `pcre` Use old PCRE implementation;
  1039. * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
  1040. * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
  1041. * * `noregex` Don't use a regex: super fast, really dumb.
  1042. * @return boolean
  1043. * @static
  1044. * @access public
  1045. */
  1046. public static function validateAddress($address, $patternselect = 'auto')
  1047. {
  1048. //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
  1049. if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) {
  1050. return false;
  1051. }
  1052. if (!$patternselect or $patternselect == 'auto') {
  1053. //Check this constant first so it works when extension_loaded() is disabled by safe mode
  1054. //Constant was added in PHP 5.2.4
  1055. if (defined('PCRE_VERSION')) {
  1056. //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2
  1057. if (version_compare(PCRE_VERSION, '8.0.3') >= 0) {
  1058. $patternselect = 'pcre8';
  1059. } else {
  1060. $patternselect = 'pcre';
  1061. }
  1062. } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) {
  1063. //Fall back to older PCRE
  1064. $patternselect = 'pcre';
  1065. } else {
  1066. //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
  1067. if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
  1068. $patternselect = 'php';
  1069. } else {
  1070. $patternselect = 'noregex';
  1071. }
  1072. }
  1073. }
  1074. switch ($patternselect) {
  1075. case 'pcre8':
  1076. /**
  1077. * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains.
  1078. * @link http://squiloople.com/2009/12/20/email-address-validation/
  1079. * @copyright 2009-2010 Michael Rushton
  1080. * Feel free to use and redistribute this code. But please keep this copyright notice.
  1081. */
  1082. return (boolean)preg_match(
  1083. '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
  1084. '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
  1085. '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
  1086. '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
  1087. '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
  1088. '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
  1089. '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
  1090. '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  1091. '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
  1092. $address
  1093. );
  1094. case 'pcre':
  1095. //An older regex that doesn't need a recent PCRE
  1096. return (boolean)preg_match(
  1097. '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
  1098. '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
  1099. '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
  1100. '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
  1101. '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
  1102. '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
  1103. '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
  1104. '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
  1105. '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  1106. '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
  1107. $address
  1108. );
  1109. case 'html5':
  1110. /**
  1111. * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
  1112. * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
  1113. */
  1114. return (boolean)preg_match(
  1115. '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
  1116. '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
  1117. $address
  1118. );
  1119. case 'noregex':
  1120. //No PCRE! Do something _very_ approximate!
  1121. //Check the address is 3 chars or longer and contains an @ that's not the first or last char
  1122. return (strlen($address) >= 3
  1123. and strpos($address, '@') >= 1
  1124. and strpos($address, '@') != strlen($address) - 1);
  1125. case 'php':
  1126. default:
  1127. return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
  1128. }
  1129. }
  1130.  
  1131. /**
  1132. * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the
  1133. * "intl" and "mbstring" PHP extensions.
  1134. * @return bool "true" if required functions for IDN support are present
  1135. */
  1136. public function idnSupported()
  1137. {
  1138. // @TODO: Write our own "idn_to_ascii" function for PHP <= 5.2.
  1139. return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding');
  1140. }
  1141.  
  1142. /**
  1143. * Converts IDN in given email address to its ASCII form, also known as punycode, if possible.
  1144. * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.
  1145. * This function silently returns unmodified address if:
  1146. * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
  1147. * - Conversion to punycode is impossible (e.g. required PHP functions are not available)
  1148. * or fails for any reason (e.g. domain has characters not allowed in an IDN)
  1149. * @see PHPMailer::$CharSet
  1150. * @param string $address The email address to convert
  1151. * @return string The encoded address in ASCII form
  1152. */
  1153. public function punyencodeAddress($address)
  1154. {
  1155. // Verify we have required functions, CharSet, and at-sign.
  1156. if ($this->idnSupported() and
  1157. !empty($this->CharSet) and
  1158. ($pos = strrpos($address, '@')) !== false) {
  1159. $domain = substr($address, ++$pos);
  1160. // Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
  1161. if ($this->has8bitChars($domain) and @mb_check_encoding($domain, $this->CharSet)) {
  1162. $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet);
  1163. if (($punycode = defined('INTL_IDNA_VARIANT_UTS46') ?
  1164. idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46) :
  1165. idn_to_ascii($domain)) !== false) {
  1166. return substr($address, 0, $pos) . $punycode;
  1167. }
  1168. }
  1169. }
  1170. return $address;
  1171. }
  1172.  
  1173. /**
  1174. * Create a message and send it.
  1175. * Uses the sending method specified by $Mailer.
  1176. * @throws phpmailerException
  1177. * @return boolean false on error - See the ErrorInfo property for details of the error.
  1178. */
  1179. public function send()
  1180. {
  1181. try {
  1182. if (!$this->preSend()) {
  1183. return false;
  1184. }
  1185. return $this->postSend();
  1186. } catch (phpmailerException $exc) {
  1187. $this->mailHeader = '';
  1188. $this->setError($exc->getMessage());
  1189. if ($this->exceptions) {
  1190. throw $exc;
  1191. }
  1192. return false;
  1193. }
  1194. }
  1195.  
  1196. /**
  1197. * Prepare a message for sending.
  1198. * @throws phpmailerException
  1199. * @return boolean
  1200. */
  1201. public function preSend()
  1202. {
  1203. try {
  1204. $this->error_count = 0; // Reset errors
  1205. $this->mailHeader = '';
  1206.  
  1207. // Dequeue recipient and Reply-To addresses with IDN
  1208. foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
  1209. $params[1] = $this->punyencodeAddress($params[1]);
  1210. call_user_func_array(array($this, 'addAnAddress'), $params);
  1211. }
  1212. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  1213. throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
  1214. }
  1215.  
  1216. // Validate From, Sender, and ConfirmReadingTo addresses
  1217. foreach (array('From', 'Sender', 'ConfirmReadingTo') as $address_kind) {
  1218. $this->$address_kind = trim($this->$address_kind);
  1219. if (empty($this->$address_kind)) {
  1220. continue;
  1221. }
  1222. $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
  1223. if (!$this->validateAddress($this->$address_kind)) {
  1224. $error_message = $this->lang('invalid_address') . $this->$address_kind;
  1225. $this->setError($error_message);
  1226. $this->edebug($error_message);
  1227. if ($this->exceptions) {
  1228. throw new phpmailerException($error_message);
  1229. }
  1230. return false;
  1231. }
  1232. }
  1233.  
  1234. // Set whether the message is multipart/alternative
  1235. if (!empty($this->AltBody)) {
  1236. $this->ContentType = 'multipart/alternative';
  1237. }
  1238.  
  1239. $this->setMessageType();
  1240. // Refuse to send an empty message unless we are specifically allowing it
  1241. if (!$this->AllowEmpty and empty($this->Body)) {
  1242. throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
  1243. }
  1244.  
  1245. // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
  1246. $this->MIMEHeader = '';
  1247. $this->MIMEBody = $this->createBody();
  1248. // createBody may have added some headers, so retain them
  1249. $tempheaders = $this->MIMEHeader;
  1250. $this->MIMEHeader = $this->createHeader();
  1251. $this->MIMEHeader .= $tempheaders;
  1252.  
  1253. // To capture the complete message when using mail(), create
  1254. // an extra header list which createHeader() doesn't fold in
  1255. if ($this->Mailer == 'mail') {
  1256. if (count($this->to) > 0) {
  1257. $this->mailHeader .= $this->addrAppend('To', $this->to);
  1258. } else {
  1259. $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
  1260. }
  1261. $this->mailHeader .= $this->headerLine(
  1262. 'Subject',
  1263. $this->encodeHeader($this->secureHeader(trim($this->Subject)))
  1264. );
  1265. }
  1266.  
  1267. // Sign with DKIM if enabled
  1268. if (!empty($this->DKIM_domain)
  1269. && !empty($this->DKIM_private)
  1270. && !empty($this->DKIM_selector)
  1271. && file_exists($this->DKIM_private)) {
  1272. $header_dkim = $this->DKIM_Add(
  1273. $this->MIMEHeader . $this->mailHeader,
  1274. $this->encodeHeader($this->secureHeader($this->Subject)),
  1275. $this->MIMEBody
  1276. );
  1277. $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
  1278. str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
  1279. }
  1280. return true;
  1281. } catch (phpmailerException $exc) {
  1282. $this->setError($exc->getMessage());
  1283. if ($this->exceptions) {
  1284. throw $exc;
  1285. }
  1286. return false;
  1287. }
  1288. }
  1289.  
  1290. /**
  1291. * Actually send a message.
  1292. * Send the email via the selected mechanism
  1293. * @throws phpmailerException
  1294. * @return boolean
  1295. */
  1296. public function postSend()
  1297. {
  1298. try {
  1299. // Choose the mailer and send through it
  1300. switch ($this->Mailer) {
  1301. case 'sendmail':
  1302. case 'qmail':
  1303. return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
  1304. case 'smtp':
  1305. return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
  1306. case 'mail':
  1307. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  1308. default:
  1309. $sendMethod = $this->Mailer.'Send';
  1310. if (method_exists($this, $sendMethod)) {
  1311. return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
  1312. }
  1313.  
  1314. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  1315. }
  1316. } catch (phpmailerException $exc) {
  1317. $this->setError($exc->getMessage());
  1318. $this->edebug($exc->getMessage());
  1319. if ($this->exceptions) {
  1320. throw $exc;
  1321. }
  1322. }
  1323. return false;
  1324. }
  1325.  
  1326. /**
  1327. * Send mail using the $Sendmail program.
  1328. * @param string $header The message headers
  1329. * @param string $body The message body
  1330. * @see PHPMailer::$Sendmail
  1331. * @throws phpmailerException
  1332. * @access protected
  1333. * @return boolean
  1334. */
  1335. protected function sendmailSend($header, $body)
  1336. {
  1337. if ($this->Sender != '') {
  1338. if ($this->Mailer == 'qmail') {
  1339. $sendmail = sprintf('%s -f%s', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  1340. } else {
  1341. $sendmail = sprintf('%s -oi -f%s -t', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  1342. }
  1343. } else {
  1344. if ($this->Mailer == 'qmail') {
  1345. $sendmail = sprintf('%s', escapeshellcmd($this->Sendmail));
  1346. } else {
  1347. $sendmail = sprintf('%s -oi -t', escapeshellcmd($this->Sendmail));
  1348. }
  1349. }
  1350. if ($this->SingleTo) {
  1351. foreach ($this->SingleToArray as $toAddr) {
  1352. if (!@$mail = popen($sendmail, 'w')) {
  1353. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1354. }
  1355. fputs($mail, 'To: ' . $toAddr . "\n");
  1356. fputs($mail, $header);
  1357. fputs($mail, $body);
  1358. $result = pclose($mail);
  1359. $this->doCallback(
  1360. ($result == 0),
  1361. array($toAddr),
  1362. $this->cc,
  1363. $this->bcc,
  1364. $this->Subject,
  1365. $body,
  1366. $this->From
  1367. );
  1368. if ($result != 0) {
  1369. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1370. }
  1371. }
  1372. } else {
  1373. if (!@$mail = popen($sendmail, 'w')) {
  1374. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1375. }
  1376. fputs($mail, $header);
  1377. fputs($mail, $body);
  1378. $result = pclose($mail);
  1379. $this->doCallback(
  1380. ($result == 0),
  1381. $this->to,
  1382. $this->cc,
  1383. $this->bcc,
  1384. $this->Subject,
  1385. $body,
  1386. $this->From
  1387. );
  1388. if ($result != 0) {
  1389. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1390. }
  1391. }
  1392. return true;
  1393. }
  1394.  
  1395. /**
  1396. * Send mail using the PHP mail() function.
  1397. * @param string $header The message headers
  1398. * @param string $body The message body
  1399. * @link http://www.php.net/manual/en/book.mail.php
  1400. * @throws phpmailerException
  1401. * @access protected
  1402. * @return boolean
  1403. */
  1404. protected function mailSend($header, $body)
  1405. {
  1406. $toArr = array();
  1407. foreach ($this->to as $toaddr) {
  1408. $toArr[] = $this->addrFormat($toaddr);
  1409. }
  1410. $to = implode(', ', $toArr);
  1411.  
  1412. if (empty($this->Sender)) {
  1413. $params = ' ';
  1414. } else {
  1415. $params = sprintf('-f%s', $this->Sender);
  1416. }
  1417. if ($this->Sender != '' and !ini_get('safe_mode')) {
  1418. $old_from = ini_get('sendmail_from');
  1419. ini_set('sendmail_from', $this->Sender);
  1420. }
  1421. $result = false;
  1422. if ($this->SingleTo && count($toArr) > 1) {
  1423. foreach ($toArr as $toAddr) {
  1424. $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
  1425. $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1426. }
  1427. } else {
  1428. $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
  1429. $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1430. }
  1431. if (isset($old_from)) {
  1432. ini_set('sendmail_from', $old_from);
  1433. }
  1434. if (!$result) {
  1435. throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
  1436. }
  1437. return true;
  1438. }
  1439.  
  1440. /**
  1441. * Get an instance to use for SMTP operations.
  1442. * Override this function to load your own SMTP implementation
  1443. * @return SMTP
  1444. */
  1445. public function getSMTPInstance()
  1446. {
  1447. if (!is_object($this->smtp)) {
  1448. $this->smtp = new SMTP;
  1449. }
  1450. return $this->smtp;
  1451. }
  1452.  
  1453. /**
  1454. * Send mail via SMTP.
  1455. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  1456. * Uses the PHPMailerSMTP class by default.
  1457. * @see PHPMailer::getSMTPInstance() to use a different class.
  1458. * @param string $header The message headers
  1459. * @param string $body The message body
  1460. * @throws phpmailerException
  1461. * @uses SMTP
  1462. * @access protected
  1463. * @return boolean
  1464. */
  1465. protected function smtpSend($header, $body)
  1466. {
  1467. $bad_rcpt = array();
  1468. if (!$this->smtpConnect($this->SMTPOptions)) {
  1469. throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
  1470. }
  1471. if ('' == $this->Sender) {
  1472. $smtp_from = $this->From;
  1473. } else {
  1474. $smtp_from = $this->Sender;
  1475. }
  1476. if (!$this->smtp->mail($smtp_from)) {
  1477. $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
  1478. throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
  1479. }
  1480.  
  1481. // Attempt to send to all recipients
  1482. foreach (array($this->to, $this->cc, $this->bcc) as $togroup) {
  1483. foreach ($togroup as $to) {
  1484. if (!$this->smtp->recipient($to[0])) {
  1485. $error = $this->smtp->getError();
  1486. $bad_rcpt[] = array('to' => $to[0], 'error' => $error['detail']);
  1487. $isSent = false;
  1488. } else {
  1489. $isSent = true;
  1490. }
  1491. $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From);
  1492. }
  1493. }
  1494.  
  1495. // Only send the DATA command if we have viable recipients
  1496. if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
  1497. throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
  1498. }
  1499. if ($this->SMTPKeepAlive) {
  1500. $this->smtp->reset();
  1501. } else {
  1502. $this->smtp->quit();
  1503. $this->smtp->close();
  1504. }
  1505. //Create error message for any bad addresses
  1506. if (count($bad_rcpt) > 0) {
  1507. $errstr = '';
  1508. foreach ($bad_rcpt as $bad) {
  1509. $errstr .= $bad['to'] . ': ' . $bad['error'];
  1510. }
  1511. throw new phpmailerException(
  1512. $this->lang('recipients_failed') . $errstr,
  1513. self::STOP_CONTINUE
  1514. );
  1515. }
  1516. return true;
  1517. }
  1518.  
  1519. /**
  1520. * Initiate a connection to an SMTP server.
  1521. * Returns false if the operation failed.
  1522. * @param array $options An array of options compatible with stream_context_create()
  1523. * @uses SMTP
  1524. * @access public
  1525. * @throws phpmailerException
  1526. * @return boolean
  1527. */
  1528. public function smtpConnect($options = array())
  1529. {
  1530. if (is_null($this->smtp)) {
  1531. $this->smtp = $this->getSMTPInstance();
  1532. }
  1533.  
  1534. // Already connected?
  1535. if ($this->smtp->connected()) {
  1536. return true;
  1537. }
  1538.  
  1539. $this->smtp->setTimeout($this->Timeout);
  1540. $this->smtp->setDebugLevel($this->SMTPDebug);
  1541. $this->smtp->setDebugOutput($this->Debugoutput);
  1542. $this->smtp->setVerp($this->do_verp);
  1543. $hosts = explode(';', $this->Host);
  1544. $lastexception = null;
  1545.  
  1546. foreach ($hosts as $hostentry) {
  1547. $hostinfo = array();
  1548. if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
  1549. // Not a valid host entry
  1550. continue;
  1551. }
  1552. // $hostinfo[2]: optional ssl or tls prefix
  1553. // $hostinfo[3]: the hostname
  1554. // $hostinfo[4]: optional port number
  1555. // The host string prefix can temporarily override the current setting for SMTPSecure
  1556. // If it's not specified, the default value is used
  1557. $prefix = '';
  1558. $secure = $this->SMTPSecure;
  1559. $tls = ($this->SMTPSecure == 'tls');
  1560. if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
  1561. $prefix = 'ssl://';
  1562. $tls = false; // Can't have SSL and TLS at the same time
  1563. $secure = 'ssl';
  1564. } elseif ($hostinfo[2] == 'tls') {
  1565. $tls = true;
  1566. // tls doesn't use a prefix
  1567. $secure = 'tls';
  1568. }
  1569. //Do we need the OpenSSL extension?
  1570. $sslext = defined('OPENSSL_ALGO_SHA1');
  1571. if ('tls' === $secure or 'ssl' === $secure) {
  1572. //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
  1573. if (!$sslext) {
  1574. throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL);
  1575. }
  1576. }
  1577. $host = $hostinfo[3];
  1578. $port = $this->Port;
  1579. $tport = (integer)$hostinfo[4];
  1580. if ($tport > 0 and $tport < 65536) {
  1581. $port = $tport;
  1582. }
  1583. if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
  1584. try {
  1585. if ($this->Helo) {
  1586. $hello = $this->Helo;
  1587. } else {
  1588. $hello = $this->serverHostname();
  1589. }
  1590. $this->smtp->hello($hello);
  1591. //Automatically enable TLS encryption if:
  1592. // * it's not disabled
  1593. // * we have openssl extension
  1594. // * we are not already using SSL
  1595. // * the server offers STARTTLS
  1596. if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) {
  1597. $tls = true;
  1598. }
  1599. if ($tls) {
  1600. if (!$this->smtp->startTLS()) {
  1601. throw new phpmailerException($this->lang('connect_host'));
  1602. }
  1603. // We must resend HELO after tls negotiation
  1604. $this->smtp->hello($hello);
  1605. }
  1606. if ($this->SMTPAuth) {
  1607. if (!$this->smtp->authenticate(
  1608. $this->Username,
  1609. $this->Password,
  1610. $this->AuthType,
  1611. $this->Realm,
  1612. $this->Workstation
  1613. )
  1614. ) {
  1615. throw new phpmailerException($this->lang('authenticate'));
  1616. }
  1617. }
  1618. return true;
  1619. } catch (phpmailerException $exc) {
  1620. $lastexception = $exc;
  1621. $this->edebug($exc->getMessage());
  1622. // We must have connected, but then failed TLS or Auth, so close connection nicely
  1623. $this->smtp->quit();
  1624. }
  1625. }
  1626. }
  1627. // If we get here, all connection attempts have failed, so close connection hard
  1628. $this->smtp->close();
  1629. // As we've caught all exceptions, just report whatever the last one was
  1630. if ($this->exceptions and !is_null($lastexception)) {
  1631. throw $lastexception;
  1632. }
  1633. return false;
  1634. }
  1635.  
  1636. /**
  1637. * Close the active SMTP session if one exists.
  1638. * @return void
  1639. */
  1640. public function smtpClose()
  1641. {
  1642. if ($this->smtp !== null) {
  1643. if ($this->smtp->connected()) {
  1644. $this->smtp->quit();
  1645. $this->smtp->close();
  1646. }
  1647. }
  1648. }
  1649.  
  1650. /**
  1651. * Set the language for error messages.
  1652. * Returns false if it cannot load the language file.
  1653. * The default language is English.
  1654. * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
  1655. * @param string $lang_path Path to the language file directory, with trailing separator (slash)
  1656. * @return boolean
  1657. * @access public
  1658. */
  1659. public function setLanguage($langcode = 'en', $lang_path = '')
  1660. {
  1661. // Define full set of translatable strings in English
  1662. $PHPMAILER_LANG = array(
  1663. 'authenticate' => 'SMTP Error: Could not authenticate.',
  1664. 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  1665. 'data_not_accepted' => 'SMTP Error: data not accepted.',
  1666. 'empty_message' => 'Message body empty',
  1667. 'encoding' => 'Unknown encoding: ',
  1668. 'execute' => 'Could not execute: ',
  1669. 'file_access' => 'Could not access file: ',
  1670. 'file_open' => 'File Error: Could not open file: ',
  1671. 'from_failed' => 'The following From address failed: ',
  1672. 'instantiate' => 'Could not instantiate mail function.',
  1673. 'invalid_address' => 'Invalid address: ',
  1674. 'mailer_not_supported' => ' mailer is not supported.',
  1675. 'provide_address' => 'You must provide at least one recipient email address.',
  1676. 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  1677. 'signing' => 'Signing Error: ',
  1678. 'smtp_connect_failed' => 'SMTP connect() failed.',
  1679. 'smtp_error' => 'SMTP server error: ',
  1680. 'variable_set' => 'Cannot set or reset variable: ',
  1681. 'extension_missing' => 'Extension missing: '
  1682. );
  1683. if (empty($lang_path)) {
  1684. // Calculate an absolute path so it can work if CWD is not here
  1685. $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR;
  1686. }
  1687. $foundlang = true;
  1688. $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
  1689. // There is no English translation file
  1690. if ($langcode != 'en') {
  1691. // Make sure language file path is readable
  1692. if (!is_readable($lang_file)) {
  1693. $foundlang = false;
  1694. } else {
  1695. // Overwrite language-specific strings.
  1696. // This way we'll never have missing translation keys.
  1697. $foundlang = include $lang_file;
  1698. }
  1699. }
  1700. $this->language = $PHPMAILER_LANG;
  1701. return (boolean)$foundlang; // Returns false if language not found
  1702. }
  1703.  
  1704. /**
  1705. * Get the array of strings for the current language.
  1706. * @return array
  1707. */
  1708. public function getTranslations()
  1709. {
  1710. return $this->language;
  1711. }
  1712.  
  1713. /**
  1714. * Create recipient headers.
  1715. * @access public
  1716. * @param string $type
  1717. * @param array $addr An array of recipient,
  1718. * where each recipient is a 2-element indexed array with element 0 containing an address
  1719. * and element 1 containing a name, like:
  1720. * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User'))
  1721. * @return string
  1722. */
  1723. public function addrAppend($type, $addr)
  1724. {
  1725. $addresses = array();
  1726. foreach ($addr as $address) {
  1727. $addresses[] = $this->addrFormat($address);
  1728. }
  1729. return $type . ': ' . implode(', ', $addresses) . $this->LE;
  1730. }
  1731.  
  1732. /**
  1733. * Format an address for use in a message header.
  1734. * @access public
  1735. * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name
  1736. * like array('joe@example.com', 'Joe User')
  1737. * @return string
  1738. */
  1739. public function addrFormat($addr)
  1740. {
  1741. if (empty($addr[1])) { // No name provided
  1742. return $this->secureHeader($addr[0]);
  1743. } else {
  1744. return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
  1745. $addr[0]
  1746. ) . '>';
  1747. }
  1748. }
  1749.  
  1750. /**
  1751. * Word-wrap message.
  1752. * For use with mailers that do not automatically perform wrapping
  1753. * and for quoted-printable encoded messages.
  1754. * Original written by philippe.
  1755. * @param string $message The message to wrap
  1756. * @param integer $length The line length to wrap to
  1757. * @param boolean $qp_mode Whether to run in Quoted-Printable mode
  1758. * @access public
  1759. * @return string
  1760. */
  1761. public function wrapText($message, $length, $qp_mode = false)
  1762. {
  1763. if ($qp_mode) {
  1764. $soft_break = sprintf(' =%s', $this->LE);
  1765. } else {
  1766. $soft_break = $this->LE;
  1767. }
  1768. // If utf-8 encoding is used, we will need to make sure we don't
  1769. // split multibyte characters when we wrap
  1770. $is_utf8 = (strtolower($this->CharSet) == 'utf-8');
  1771. $lelen = strlen($this->LE);
  1772. $crlflen = strlen(self::CRLF);
  1773.  
  1774. $message = $this->fixEOL($message);
  1775. //Remove a trailing line break
  1776. if (substr($message, -$lelen) == $this->LE) {
  1777. $message = substr($message, 0, -$lelen);
  1778. }
  1779.  
  1780. //Split message into lines
  1781. $lines = explode($this->LE, $message);
  1782. //Message will be rebuilt in here
  1783. $message = '';
  1784. foreach ($lines as $line) {
  1785. $words = explode(' ', $line);
  1786. $buf = '';
  1787. $firstword = true;
  1788. foreach ($words as $word) {
  1789. if ($qp_mode and (strlen($word) > $length)) {
  1790. $space_left = $length - strlen($buf) - $crlflen;
  1791. if (!$firstword) {
  1792. if ($space_left > 20) {
  1793. $len = $space_left;
  1794. if ($is_utf8) {
  1795. $len = $this->utf8CharBoundary($word, $len);
  1796. } elseif (substr($word, $len - 1, 1) == '=') {
  1797. $len--;
  1798. } elseif (substr($word, $len - 2, 1) == '=') {
  1799. $len -= 2;
  1800. }
  1801. $part = substr($word, 0, $len);
  1802. $word = substr($word, $len);
  1803. $buf .= ' ' . $part;
  1804. $message .= $buf . sprintf('=%s', self::CRLF);
  1805. } else {
  1806. $message .= $buf . $soft_break;
  1807. }
  1808. $buf = '';
  1809. }
  1810. while (strlen($word) > 0) {
  1811. if ($length <= 0) {
  1812. break;
  1813. }
  1814. $len = $length;
  1815. if ($is_utf8) {
  1816. $len = $this->utf8CharBoundary($word, $len);
  1817. } elseif (substr($word, $len - 1, 1) == '=') {
  1818. $len--;
  1819. } elseif (substr($word, $len - 2, 1) == '=') {
  1820. $len -= 2;
  1821. }
  1822. $part = substr($word, 0, $len);
  1823. $word = substr($word, $len);
  1824.  
  1825. if (strlen($word) > 0) {
  1826. $message .= $part . sprintf('=%s', self::CRLF);
  1827. } else {
  1828. $buf = $part;
  1829. }
  1830. }
  1831. } else {
  1832. $buf_o = $buf;
  1833. if (!$firstword) {
  1834. $buf .= ' ';
  1835. }
  1836. $buf .= $word;
  1837.  
  1838. if (strlen($buf) > $length and $buf_o != '') {
  1839. $message .= $buf_o . $soft_break;
  1840. $buf = $word;
  1841. }
  1842. }
  1843. $firstword = false;
  1844. }
  1845. $message .= $buf . self::CRLF;
  1846. }
  1847.  
  1848. return $message;
  1849. }
  1850.  
  1851. /**
  1852. * Find the last character boundary prior to $maxLength in a utf-8
  1853. * quoted-printable encoded string.
  1854. * Original written by Colin Brown.
  1855. * @access public
  1856. * @param string $encodedText utf-8 QP text
  1857. * @param integer $maxLength Find the last character boundary prior to this length
  1858. * @return integer
  1859. */
  1860. public function utf8CharBoundary($encodedText, $maxLength)
  1861. {
  1862. $foundSplitPos = false;
  1863. $lookBack = 3;
  1864. while (!$foundSplitPos) {
  1865. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  1866. $encodedCharPos = strpos($lastChunk, '=');
  1867. if (false !== $encodedCharPos) {
  1868. // Found start of encoded character byte within $lookBack block.
  1869. // Check the encoded byte value (the 2 chars after the '=')
  1870. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  1871. $dec = hexdec($hex);
  1872. if ($dec < 128) {
  1873. // Single byte character.
  1874. // If the encoded char was found at pos 0, it will fit
  1875. // otherwise reduce maxLength to start of the encoded char
  1876. if ($encodedCharPos > 0) {
  1877. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  1878. }
  1879. $foundSplitPos = true;
  1880. } elseif ($dec >= 192) {
  1881. // First byte of a multi byte character
  1882. // Reduce maxLength to split at start of character
  1883. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  1884. $foundSplitPos = true;
  1885. } elseif ($dec < 192) {
  1886. // Middle byte of a multi byte character, look further back
  1887. $lookBack += 3;
  1888. }
  1889. } else {
  1890. // No encoded character found
  1891. $foundSplitPos = true;
  1892. }
  1893. }
  1894. return $maxLength;
  1895. }
  1896.  
  1897. /**
  1898. * Apply word wrapping to the message body.
  1899. * Wraps the message body to the number of chars set in the WordWrap property.
  1900. * You should only do this to plain-text bodies as wrapping HTML tags may break them.
  1901. * This is called automatically by createBody(), so you don't need to call it yourself.
  1902. * @access public
  1903. * @return void
  1904. */
  1905. public function setWordWrap()
  1906. {
  1907. if ($this->WordWrap < 1) {
  1908. return;
  1909. }
  1910.  
  1911. switch ($this->message_type) {
  1912. case 'alt':
  1913. case 'alt_inline':
  1914. case 'alt_attach':
  1915. case 'alt_inline_attach':
  1916. $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
  1917. break;
  1918. default:
  1919. $this->Body = $this->wrapText($this->Body, $this->WordWrap);
  1920. break;
  1921. }
  1922. }
  1923.  
  1924. /**
  1925. * Assemble message headers.
  1926. * @access public
  1927. * @return string The assembled headers
  1928. */
  1929. public function createHeader()
  1930. {
  1931. $result = '';
  1932.  
  1933. if ($this->MessageDate == '') {
  1934. $this->MessageDate = self::rfcDate();
  1935. }
  1936. $result .= $this->headerLine('Date', $this->MessageDate);
  1937.  
  1938. // To be created automatically by mail()
  1939. if ($this->SingleTo) {
  1940. if ($this->Mailer != 'mail') {
  1941. foreach ($this->to as $toaddr) {
  1942. $this->SingleToArray[] = $this->addrFormat($toaddr);
  1943. }
  1944. }
  1945. } else {
  1946. if (count($this->to) > 0) {
  1947. if ($this->Mailer != 'mail') {
  1948. $result .= $this->addrAppend('To', $this->to);
  1949. }
  1950. } elseif (count($this->cc) == 0) {
  1951. $result .= $this->headerLine('To', 'undisclosed-recipients:;');
  1952. }
  1953. }
  1954.  
  1955. $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName)));
  1956.  
  1957. // sendmail and mail() extract Cc from the header before sending
  1958. if (count($this->cc) > 0) {
  1959. $result .= $this->addrAppend('Cc', $this->cc);
  1960. }
  1961.  
  1962. // sendmail and mail() extract Bcc from the header before sending
  1963. if ((
  1964. $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail'
  1965. )
  1966. and count($this->bcc) > 0
  1967. ) {
  1968. $result .= $this->addrAppend('Bcc', $this->bcc);
  1969. }
  1970.  
  1971. if (count($this->ReplyTo) > 0) {
  1972. $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
  1973. }
  1974.  
  1975. // mail() sets the subject itself
  1976. if ($this->Mailer != 'mail') {
  1977. $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
  1978. }
  1979.  
  1980. if ($this->MessageID != '') {
  1981. $this->lastMessageID = $this->MessageID;
  1982. } else {
  1983. $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
  1984. }
  1985. $result .= $this->headerLine('Message-ID', $this->lastMessageID);
  1986. if (!is_null($this->Priority)) {
  1987. $result .= $this->headerLine('X-Priority', $this->Priority);
  1988. }
  1989. if ($this->XMailer == '') {
  1990. $result .= $this->headerLine(
  1991. 'X-Mailer',
  1992. 'PHPMailer ' . $this->Version . ' (https://github.com/PHPMailer/PHPMailer)'
  1993. );
  1994. } else {
  1995. $myXmailer = trim($this->XMailer);
  1996. if ($myXmailer) {
  1997. $result .= $this->headerLine('X-Mailer', $myXmailer);
  1998. }
  1999. }
  2000.  
  2001. if ($this->ConfirmReadingTo != '') {
  2002. $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
  2003. }
  2004.  
  2005. // Add custom headers
  2006. foreach ($this->CustomHeader as $header) {
  2007. $result .= $this->headerLine(
  2008. trim($header[0]),
  2009. $this->encodeHeader(trim($header[1]))
  2010. );
  2011. }
  2012. if (!$this->sign_key_file) {
  2013. $result .= $this->headerLine('MIME-Version', '1.0');
  2014. $result .= $this->getMailMIME();
  2015. }
  2016.  
  2017. return $result;
  2018. }
  2019.  
  2020. /**
  2021. * Get the message MIME type headers.
  2022. * @access public
  2023. * @return string
  2024. */
  2025. public function getMailMIME()
  2026. {
  2027. $result = '';
  2028. $ismultipart = true;
  2029. switch ($this->message_type) {
  2030. case 'inline':
  2031. $result .= $this->headerLine('Content-Type', 'multipart/related;');
  2032. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  2033. break;
  2034. case 'attach':
  2035. case 'inline_attach':
  2036. case 'alt_attach':
  2037. case 'alt_inline_attach':
  2038. $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
  2039. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  2040. break;
  2041. case 'alt':
  2042. case 'alt_inline':
  2043. $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
  2044. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  2045. break;
  2046. default:
  2047. // Catches case 'plain': and case '':
  2048. $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
  2049. $ismultipart = false;
  2050. break;
  2051. }
  2052. // RFC1341 part 5 says 7bit is assumed if not specified
  2053. if ($this->Encoding != '7bit') {
  2054. // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
  2055. if ($ismultipart) {
  2056. if ($this->Encoding == '8bit') {
  2057. $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
  2058. }
  2059. // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
  2060. } else {
  2061. $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
  2062. }
  2063. }
  2064.  
  2065. if ($this->Mailer != 'mail') {
  2066. $result .= $this->LE;
  2067. }
  2068.  
  2069. return $result;
  2070. }
  2071.  
  2072. /**
  2073. * Returns the whole MIME message.
  2074. * Includes complete headers and body.
  2075. * Only valid post preSend().
  2076. * @see PHPMailer::preSend()
  2077. * @access public
  2078. * @return string
  2079. */
  2080. public function getSentMIMEMessage()
  2081. {
  2082. return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . self::CRLF . self::CRLF . $this->MIMEBody;
  2083. }
  2084.  
  2085. /**
  2086. * Assemble the message body.
  2087. * Returns an empty string on failure.
  2088. * @access public
  2089. * @throws phpmailerException
  2090. * @return string The assembled message body
  2091. */
  2092. public function createBody()
  2093. {
  2094. $body = '';
  2095. //Create unique IDs and preset boundaries
  2096. $this->uniqueid = md5(uniqid(time()));
  2097. $this->boundary[1] = 'b1_' . $this->uniqueid;
  2098. $this->boundary[2] = 'b2_' . $this->uniqueid;
  2099. $this->boundary[3] = 'b3_' . $this->uniqueid;
  2100.  
  2101. if ($this->sign_key_file) {
  2102. $body .= $this->getMailMIME() . $this->LE;
  2103. }
  2104.  
  2105. $this->setWordWrap();
  2106.  
  2107. $bodyEncoding = $this->Encoding;
  2108. $bodyCharSet = $this->CharSet;
  2109. //Can we do a 7-bit downgrade?
  2110. if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) {
  2111. $bodyEncoding = '7bit';
  2112. $bodyCharSet = 'us-ascii';
  2113. }
  2114. //If lines are too long, and we're not already using an encoding that will shorten them,
  2115. //change to quoted-printable transfer encoding
  2116. if ('base64' != $this->Encoding and self::hasLineLongerThanMax($this->Body)) {
  2117. $this->Encoding = 'quoted-printable';
  2118. $bodyEncoding = 'quoted-printable';
  2119. }
  2120.  
  2121. $altBodyEncoding = $this->Encoding;
  2122. $altBodyCharSet = $this->CharSet;
  2123. //Can we do a 7-bit downgrade?
  2124. if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) {
  2125. $altBodyEncoding = '7bit';
  2126. $altBodyCharSet = 'us-ascii';
  2127. }
  2128. //If lines are too long, and we're not already using an encoding that will shorten them,
  2129. //change to quoted-printable transfer encoding
  2130. if ('base64' != $altBodyEncoding and self::hasLineLongerThanMax($this->AltBody)) {
  2131. $altBodyEncoding = 'quoted-printable';
  2132. }
  2133. //Use this as a preamble in all multipart message types
  2134. $mimepre = "This is a multi-part message in MIME format." . $this->LE . $this->LE;
  2135. switch ($this->message_type) {
  2136. case 'inline':
  2137. $body .= $mimepre;
  2138. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  2139. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2140. $body .= $this->LE . $this->LE;
  2141. $body .= $this->attachAll('inline', $this->boundary[1]);
  2142. break;
  2143. case 'attach':
  2144. $body .= $mimepre;
  2145. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  2146. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2147. $body .= $this->LE . $this->LE;
  2148. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2149. break;
  2150. case 'inline_attach':
  2151. $body .= $mimepre;
  2152. $body .= $this->textLine('--' . $this->boundary[1]);
  2153. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  2154. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  2155. $body .= $this->LE;
  2156. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
  2157. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2158. $body .= $this->LE . $this->LE;
  2159. $body .= $this->attachAll('inline', $this->boundary[2]);
  2160. $body .= $this->LE;
  2161. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2162. break;
  2163. case 'alt':
  2164. $body .= $mimepre;
  2165. $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  2166. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2167. $body .= $this->LE . $this->LE;
  2168. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
  2169. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2170. $body .= $this->LE . $this->LE;
  2171. if (!empty($this->Ical)) {
  2172. $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
  2173. $body .= $this->encodeString($this->Ical, $this->Encoding);
  2174. $body .= $this->LE . $this->LE;
  2175. }
  2176. $body .= $this->endBoundary($this->boundary[1]);
  2177. break;
  2178. case 'alt_inline':
  2179. $body .= $mimepre;
  2180. $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  2181. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2182. $body .= $this->LE . $this->LE;
  2183. $body .= $this->textLine('--' . $this->boundary[1]);
  2184. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  2185. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  2186. $body .= $this->LE;
  2187. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  2188. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2189. $body .= $this->LE . $this->LE;
  2190. $body .= $this->attachAll('inline', $this->boundary[2]);
  2191. $body .= $this->LE;
  2192. $body .= $this->endBoundary($this->boundary[1]);
  2193. break;
  2194. case 'alt_attach':
  2195. $body .= $mimepre;
  2196. $body .= $this->textLine('--' . $this->boundary[1]);
  2197. $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  2198. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  2199. $body .= $this->LE;
  2200. $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  2201. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2202. $body .= $this->LE . $this->LE;
  2203. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  2204. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2205. $body .= $this->LE . $this->LE;
  2206. $body .= $this->endBoundary($this->boundary[2]);
  2207. $body .= $this->LE;
  2208. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2209. break;
  2210. case 'alt_inline_attach':
  2211. $body .= $mimepre;
  2212. $body .= $this->textLine('--' . $this->boundary[1]);
  2213. $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  2214. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  2215. $body .= $this->LE;
  2216. $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  2217. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  2218. $body .= $this->LE . $this->LE;
  2219. $body .= $this->textLine('--' . $this->boundary[2]);
  2220. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  2221. $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
  2222. $body .= $this->LE;
  2223. $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
  2224. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2225. $body .= $this->LE . $this->LE;
  2226. $body .= $this->attachAll('inline', $this->boundary[3]);
  2227. $body .= $this->LE;
  2228. $body .= $this->endBoundary($this->boundary[2]);
  2229. $body .= $this->LE;
  2230. $body .= $this->attachAll('attachment', $this->boundary[1]);
  2231. break;
  2232. default:
  2233. // catch case 'plain' and case ''
  2234. $body .= $this->encodeString($this->Body, $bodyEncoding);
  2235. break;
  2236. }
  2237.  
  2238. if ($this->isError()) {
  2239. $body = '';
  2240. } elseif ($this->sign_key_file) {
  2241. try {
  2242. if (!defined('PKCS7_TEXT')) {
  2243. throw new phpmailerException($this->lang('extension_missing') . 'openssl');
  2244. }
  2245. // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
  2246. $file = tempnam(sys_get_temp_dir(), 'mail');
  2247. if (false === file_put_contents($file, $body)) {
  2248. throw new phpmailerException($this->lang('signing') . ' Could not write temp file');
  2249. }
  2250. $signed = tempnam(sys_get_temp_dir(), 'signed');
  2251. //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
  2252. if (empty($this->sign_extracerts_file)) {
  2253. $sign = @openssl_pkcs7_sign(
  2254. $file,
  2255. $signed,
  2256. 'file://' . realpath($this->sign_cert_file),
  2257. array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
  2258. null
  2259. );
  2260. } else {
  2261. $sign = @openssl_pkcs7_sign(
  2262. $file,
  2263. $signed,
  2264. 'file://' . realpath($this->sign_cert_file),
  2265. array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
  2266. null,
  2267. PKCS7_DETACHED,
  2268. $this->sign_extracerts_file
  2269. );
  2270. }
  2271. if ($sign) {
  2272. @unlink($file);
  2273. $body = file_get_contents($signed);
  2274. @unlink($signed);
  2275. //The message returned by openssl contains both headers and body, so need to split them up
  2276. $parts = explode("\n\n", $body, 2);
  2277. $this->MIMEHeader .= $parts[0] . $this->LE . $this->LE;
  2278. $body = $parts[1];
  2279. } else {
  2280. @unlink($file);
  2281. @unlink($signed);
  2282. throw new phpmailerException($this->lang('signing') . openssl_error_string());
  2283. }
  2284. } catch (phpmailerException $exc) {
  2285. $body = '';
  2286. if ($this->exceptions) {
  2287. throw $exc;
  2288. }
  2289. }
  2290. }
  2291. return $body;
  2292. }
  2293.  
  2294. /**
  2295. * Return the start of a message boundary.
  2296. * @access protected
  2297. * @param string $boundary
  2298. * @param string $charSet
  2299. * @param string $contentType
  2300. * @param string $encoding
  2301. * @return string
  2302. */
  2303. protected function getBoundary($boundary, $charSet, $contentType, $encoding)
  2304. {
  2305. $result = '';
  2306. if ($charSet == '') {
  2307. $charSet = $this->CharSet;
  2308. }
  2309. if ($contentType == '') {
  2310. $contentType = $this->ContentType;
  2311. }
  2312. if ($encoding == '') {
  2313. $encoding = $this->Encoding;
  2314. }
  2315. $result .= $this->textLine('--' . $boundary);
  2316. $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
  2317. $result .= $this->LE;
  2318. // RFC1341 part 5 says 7bit is assumed if not specified
  2319. if ($encoding != '7bit') {
  2320. $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
  2321. }
  2322. $result .= $this->LE;
  2323.  
  2324. return $result;
  2325. }
  2326.  
  2327. /**
  2328. * Return the end of a message boundary.
  2329. * @access protected
  2330. * @param string $boundary
  2331. * @return string
  2332. */
  2333. protected function endBoundary($boundary)
  2334. {
  2335. return $this->LE . '--' . $boundary . '--' . $this->LE;
  2336. }
  2337.  
  2338. /**
  2339. * Set the message type.
  2340. * PHPMailer only supports some preset message types,
  2341. * not arbitrary MIME structures.
  2342. * @access protected
  2343. * @return void
  2344. */
  2345. protected function setMessageType()
  2346. {
  2347. $type = array();
  2348. if ($this->alternativeExists()) {
  2349. $type[] = 'alt';
  2350. }
  2351. if ($this->inlineImageExists()) {
  2352. $type[] = 'inline';
  2353. }
  2354. if ($this->attachmentExists()) {
  2355. $type[] = 'attach';
  2356. }
  2357. $this->message_type = implode('_', $type);
  2358. if ($this->message_type == '') {
  2359. $this->message_type = 'plain';
  2360. }
  2361. }
  2362.  
  2363. /**
  2364. * Format a header line.
  2365. * @access public
  2366. * @param string $name
  2367. * @param string $value
  2368. * @return string
  2369. */
  2370. public function headerLine($name, $value)
  2371. {
  2372. return $name . ': ' . $value . $this->LE;
  2373. }
  2374.  
  2375. /**
  2376. * Return a formatted mail line.
  2377. * @access public
  2378. * @param string $value
  2379. * @return string
  2380. */
  2381. public function textLine($value)
  2382. {
  2383. return $value . $this->LE;
  2384. }
  2385.  
  2386. /**
  2387. * Add an attachment from a path on the filesystem.
  2388. * Returns false if the file could not be found or read.
  2389. * @param string $path Path to the attachment.
  2390. * @param string $name Overrides the attachment name.
  2391. * @param string $encoding File encoding (see $Encoding).
  2392. * @param string $type File extension (MIME) type.
  2393. * @param string $disposition Disposition to use
  2394. * @throws phpmailerException
  2395. * @return boolean
  2396. */
  2397. public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
  2398. {
  2399. try {
  2400. if (!@is_file($path)) {
  2401. throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE);
  2402. }
  2403.  
  2404. // If a MIME type is not specified, try to work it out from the file name
  2405. if ($type == '') {
  2406. $type = self::filenameToType($path);
  2407. }
  2408.  
  2409. $filename = basename($path);
  2410. if ($name == '') {
  2411. $name = $filename;
  2412. }
  2413.  
  2414. $this->attachment[] = array(
  2415. 0 => $path,
  2416. 1 => $filename,
  2417. 2 => $name,
  2418. 3 => $encoding,
  2419. 4 => $type,
  2420. 5 => false, // isStringAttachment
  2421. 6 => $disposition,
  2422. 7 => 0
  2423. );
  2424.  
  2425. } catch (phpmailerException $exc) {
  2426. $this->setError($exc->getMessage());
  2427. $this->edebug($exc->getMessage());
  2428. if ($this->exceptions) {
  2429. throw $exc;
  2430. }
  2431. return false;
  2432. }
  2433. return true;
  2434. }
  2435.  
  2436. /**
  2437. * Return the array of attachments.
  2438. * @return array
  2439. */
  2440. public function getAttachments()
  2441. {
  2442. return $this->attachment;
  2443. }
  2444.  
  2445. /**
  2446. * Attach all file, string, and binary attachments to the message.
  2447. * Returns an empty string on failure.
  2448. * @access protected
  2449. * @param string $disposition_type
  2450. * @param string $boundary
  2451. * @return string
  2452. */
  2453. protected function attachAll($disposition_type, $boundary)
  2454. {
  2455. // Return text of body
  2456. $mime = array();
  2457. $cidUniq = array();
  2458. $incl = array();
  2459.  
  2460. // Add all attachments
  2461. foreach ($this->attachment as $attachment) {
  2462. // Check if it is a valid disposition_filter
  2463. if ($attachment[6] == $disposition_type) {
  2464. // Check for string attachment
  2465. $string = '';
  2466. $path = '';
  2467. $bString = $attachment[5];
  2468. if ($bString) {
  2469. $string = $attachment[0];
  2470. } else {
  2471. $path = $attachment[0];
  2472. }
  2473.  
  2474. $inclhash = md5(serialize($attachment));
  2475. if (in_array($inclhash, $incl)) {
  2476. continue;
  2477. }
  2478. $incl[] = $inclhash;
  2479. $name = $attachment[2];
  2480. $encoding = $attachment[3];
  2481. $type = $attachment[4];
  2482. $disposition = $attachment[6];
  2483. $cid = $attachment[7];
  2484. if ($disposition == 'inline' && array_key_exists($cid, $cidUniq)) {
  2485. continue;
  2486. }
  2487. $cidUniq[$cid] = true;
  2488.  
  2489. $mime[] = sprintf('--%s%s', $boundary, $this->LE);
  2490. //Only include a filename property if we have one
  2491. if (!empty($name)) {
  2492. $mime[] = sprintf(
  2493. 'Content-Type: %s; name="%s"%s',
  2494. $type,
  2495. $this->encodeHeader($this->secureHeader($name)),
  2496. $this->LE
  2497. );
  2498. } else {
  2499. $mime[] = sprintf(
  2500. 'Content-Type: %s%s',
  2501. $type,
  2502. $this->LE
  2503. );
  2504. }
  2505. // RFC1341 part 5 says 7bit is assumed if not specified
  2506. if ($encoding != '7bit') {
  2507. $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE);
  2508. }
  2509.  
  2510. if ($disposition == 'inline') {
  2511. $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE);
  2512. }
  2513.  
  2514. // If a filename contains any of these chars, it should be quoted,
  2515. // but not otherwise: RFC2183 & RFC2045 5.1
  2516. // Fixes a warning in IETF's msglint MIME checker
  2517. // Allow for bypassing the Content-Disposition header totally
  2518. if (!(empty($disposition))) {
  2519. $encoded_name = $this->encodeHeader($this->secureHeader($name));
  2520. if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
  2521. $mime[] = sprintf(
  2522. 'Content-Disposition: %s; filename="%s"%s',
  2523. $disposition,
  2524. $encoded_name,
  2525. $this->LE . $this->LE
  2526. );
  2527. } else {
  2528. if (!empty($encoded_name)) {
  2529. $mime[] = sprintf(
  2530. 'Content-Disposition: %s; filename=%s%s',
  2531. $disposition,
  2532. $encoded_name,
  2533. $this->LE . $this->LE
  2534. );
  2535. } else {
  2536. $mime[] = sprintf(
  2537. 'Content-Disposition: %s%s',
  2538. $disposition,
  2539. $this->LE . $this->LE
  2540. );
  2541. }
  2542. }
  2543. } else {
  2544. $mime[] = $this->LE;
  2545. }
  2546.  
  2547. // Encode as string attachment
  2548. if ($bString) {
  2549. $mime[] = $this->encodeString($string, $encoding);
  2550. if ($this->isError()) {
  2551. return '';
  2552. }
  2553. $mime[] = $this->LE . $this->LE;
  2554. } else {
  2555. $mime[] = $this->encodeFile($path, $encoding);
  2556. if ($this->isError()) {
  2557. return '';
  2558. }
  2559. $mime[] = $this->LE . $this->LE;
  2560. }
  2561. }
  2562. }
  2563.  
  2564. $mime[] = sprintf('--%s--%s', $boundary, $this->LE);
  2565.  
  2566. return implode('', $mime);
  2567. }
  2568.  
  2569. /**
  2570. * Encode a file attachment in requested format.
  2571. * Returns an empty string on failure.
  2572. * @param string $path The full path to the file
  2573. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  2574. * @throws phpmailerException
  2575. * @access protected
  2576. * @return string
  2577. */
  2578. protected function encodeFile($path, $encoding = 'base64')
  2579. {
  2580. try {
  2581. if (!is_readable($path)) {
  2582. throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE);
  2583. }
  2584. $magic_quotes = get_magic_quotes_runtime();
  2585. if ($magic_quotes) {
  2586. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  2587. set_magic_quotes_runtime(false);
  2588. } else {
  2589. //Doesn't exist in PHP 5.4, but we don't need to check because
  2590. //get_magic_quotes_runtime always returns false in 5.4+
  2591. //so it will never get here
  2592. ini_set('magic_quotes_runtime', false);
  2593. }
  2594. }
  2595. $file_buffer = file_get_contents($path);
  2596. $file_buffer = $this->encodeString($file_buffer, $encoding);
  2597. if ($magic_quotes) {
  2598. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  2599. set_magic_quotes_runtime($magic_quotes);
  2600. } else {
  2601. ini_set('magic_quotes_runtime', $magic_quotes);
  2602. }
  2603. }
  2604. return $file_buffer;
  2605. } catch (Exception $exc) {
  2606. $this->setError($exc->getMessage());
  2607. return '';
  2608. }
  2609. }
  2610.  
  2611. /**
  2612. * Encode a string in requested format.
  2613. * Returns an empty string on failure.
  2614. * @param string $str The text to encode
  2615. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  2616. * @access public
  2617. * @return string
  2618. */
  2619. public function encodeString($str, $encoding = 'base64')
  2620. {
  2621. $encoded = '';
  2622. switch (strtolower($encoding)) {
  2623. case 'base64':
  2624. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  2625. break;
  2626. case '7bit':
  2627. case '8bit':
  2628. $encoded = $this->fixEOL($str);
  2629. // Make sure it ends with a line break
  2630. if (substr($encoded, -(strlen($this->LE))) != $this->LE) {
  2631. $encoded .= $this->LE;
  2632. }
  2633. break;
  2634. case 'binary':
  2635. $encoded = $str;
  2636. break;
  2637. case 'quoted-printable':
  2638. $encoded = $this->encodeQP($str);
  2639. break;
  2640. default:
  2641. $this->setError($this->lang('encoding') . $encoding);
  2642. break;
  2643. }
  2644. return $encoded;
  2645. }
  2646.  
  2647. /**
  2648. * Encode a header string optimally.
  2649. * Picks shortest of Q, B, quoted-printable or none.
  2650. * @access public
  2651. * @param string $str
  2652. * @param string $position
  2653. * @return string
  2654. */
  2655. public function encodeHeader($str, $position = 'text')
  2656. {
  2657. $matchcount = 0;
  2658. switch (strtolower($position)) {
  2659. case 'phrase':
  2660. if (!preg_match('/[\200-\377]/', $str)) {
  2661. // Can't use addslashes as we don't know the value of magic_quotes_sybase
  2662. $encoded = addcslashes($str, "\0..\37\177\\\"");
  2663. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  2664. return ($encoded);
  2665. } else {
  2666. return ("\"$encoded\"");
  2667. }
  2668. }
  2669. $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  2670. break;
  2671. /** @noinspection PhpMissingBreakStatementInspection */
  2672. case 'comment':
  2673. $matchcount = preg_match_all('/[()"]/', $str, $matches);
  2674. // Intentional fall-through
  2675. case 'text':
  2676. default:
  2677. $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  2678. break;
  2679. }
  2680.  
  2681. //There are no chars that need encoding
  2682. if ($matchcount == 0) {
  2683. return ($str);
  2684. }
  2685.  
  2686. $maxlen = 75 - 7 - strlen($this->CharSet);
  2687. // Try to select the encoding which should produce the shortest output
  2688. if ($matchcount > strlen($str) / 3) {
  2689. // More than a third of the content will need encoding, so B encoding will be most efficient
  2690. $encoding = 'B';
  2691. if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
  2692. // Use a custom function which correctly encodes and wraps long
  2693. // multibyte strings without breaking lines within a character
  2694. $encoded = $this->base64EncodeWrapMB($str, "\n");
  2695. } else {
  2696. $encoded = base64_encode($str);
  2697. $maxlen -= $maxlen % 4;
  2698. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  2699. }
  2700. } else {
  2701. $encoding = 'Q';
  2702. $encoded = $this->encodeQ($str, $position);
  2703. $encoded = $this->wrapText($encoded, $maxlen, true);
  2704. $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
  2705. }
  2706.  
  2707. $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
  2708. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  2709.  
  2710. return $encoded;
  2711. }
  2712.  
  2713. /**
  2714. * Check if a string contains multi-byte characters.
  2715. * @access public
  2716. * @param string $str multi-byte text to wrap encode
  2717. * @return boolean
  2718. */
  2719. public function hasMultiBytes($str)
  2720. {
  2721. if (function_exists('mb_strlen')) {
  2722. return (strlen($str) > mb_strlen($str, $this->CharSet));
  2723. } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  2724. return false;
  2725. }
  2726. }
  2727.  
  2728. /**
  2729. * Does a string contain any 8-bit chars (in any charset)?
  2730. * @param string $text
  2731. * @return boolean
  2732. */
  2733. public function has8bitChars($text)
  2734. {
  2735. return (boolean)preg_match('/[\x80-\xFF]/', $text);
  2736. }
  2737.  
  2738. /**
  2739. * Encode and wrap long multibyte strings for mail headers
  2740. * without breaking lines within a character.
  2741. * Adapted from a function by paravoid
  2742. * @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
  2743. * @access public
  2744. * @param string $str multi-byte text to wrap encode
  2745. * @param string $linebreak string to use as linefeed/end-of-line
  2746. * @return string
  2747. */
  2748. public function base64EncodeWrapMB($str, $linebreak = null)
  2749. {
  2750. $start = '=?' . $this->CharSet . '?B?';
  2751. $end = '?=';
  2752. $encoded = '';
  2753. if ($linebreak === null) {
  2754. $linebreak = $this->LE;
  2755. }
  2756.  
  2757. $mb_length = mb_strlen($str, $this->CharSet);
  2758. // Each line must have length <= 75, including $start and $end
  2759. $length = 75 - strlen($start) - strlen($end);
  2760. // Average multi-byte ratio
  2761. $ratio = $mb_length / strlen($str);
  2762. // Base64 has a 4:3 ratio
  2763. $avgLength = floor($length * $ratio * .75);
  2764.  
  2765. for ($i = 0; $i < $mb_length; $i += $offset) {
  2766. $lookBack = 0;
  2767. do {
  2768. $offset = $avgLength - $lookBack;
  2769. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  2770. $chunk = base64_encode($chunk);
  2771. $lookBack++;
  2772. } while (strlen($chunk) > $length);
  2773. $encoded .= $chunk . $linebreak;
  2774. }
  2775.  
  2776. // Chomp the last linefeed
  2777. $encoded = substr($encoded, 0, -strlen($linebreak));
  2778. return $encoded;
  2779. }
  2780.  
  2781. /**
  2782. * Encode a string in quoted-printable format.
  2783. * According to RFC2045 section 6.7.
  2784. * @access public
  2785. * @param string $string The text to encode
  2786. * @param integer $line_max Number of chars allowed on a line before wrapping
  2787. * @return string
  2788. * @link http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 Adapted from this comment
  2789. */
  2790. public function encodeQP($string, $line_max = 76)
  2791. {
  2792. // Use native function if it's available (>= PHP5.3)
  2793. if (function_exists('quoted_printable_encode')) {
  2794. return quoted_printable_encode($string);
  2795. }
  2796. // Fall back to a pure PHP implementation
  2797. $string = str_replace(
  2798. array('%20', '%0D%0A.', '%0D%0A', '%'),
  2799. array(' ', "\r\n=2E", "\r\n", '='),
  2800. rawurlencode($string)
  2801. );
  2802. return preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string);
  2803. }
  2804.  
  2805. /**
  2806. * Backward compatibility wrapper for an old QP encoding function that was removed.
  2807. * @see PHPMailer::encodeQP()
  2808. * @access public
  2809. * @param string $string
  2810. * @param integer $line_max
  2811. * @param boolean $space_conv
  2812. * @return string
  2813. * @deprecated Use encodeQP instead.
  2814. */
  2815. public function encodeQPphp(
  2816. $string,
  2817. $line_max = 76,
  2818. /** @noinspection PhpUnusedParameterInspection */ $space_conv = false
  2819. ) {
  2820. return $this->encodeQP($string, $line_max);
  2821. }
  2822.  
  2823. /**
  2824. * Encode a string using Q encoding.
  2825. * @link http://tools.ietf.org/html/rfc2047
  2826. * @param string $str the text to encode
  2827. * @param string $position Where the text is going to be used, see the RFC for what that means
  2828. * @access public
  2829. * @return string
  2830. */
  2831. public function encodeQ($str, $position = 'text')
  2832. {
  2833. // There should not be any EOL in the string
  2834. $pattern = '';
  2835. $encoded = str_replace(array("\r", "\n"), '', $str);
  2836. switch (strtolower($position)) {
  2837. case 'phrase':
  2838. // RFC 2047 section 5.3
  2839. $pattern = '^A-Za-z0-9!*+\/ -';
  2840. break;
  2841. /** @noinspection PhpMissingBreakStatementInspection */
  2842. case 'comment':
  2843. // RFC 2047 section 5.2
  2844. $pattern = '\(\)"';
  2845. // intentional fall-through
  2846. // for this reason we build the $pattern without including delimiters and []
  2847. case 'text':
  2848. default:
  2849. // RFC 2047 section 5.1
  2850. // Replace every high ascii, control, =, ? and _ characters
  2851. $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
  2852. break;
  2853. }
  2854. $matches = array();
  2855. if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
  2856. // If the string contains an '=', make sure it's the first thing we replace
  2857. // so as to avoid double-encoding
  2858. $eqkey = array_search('=', $matches[0]);
  2859. if (false !== $eqkey) {
  2860. unset($matches[0][$eqkey]);
  2861. array_unshift($matches[0], '=');
  2862. }
  2863. foreach (array_unique($matches[0]) as $char) {
  2864. $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  2865. }
  2866. }
  2867. // Replace every spaces to _ (more readable than =20)
  2868. return str_replace(' ', '_', $encoded);
  2869. }
  2870.  
  2871. /**
  2872. * Add a string or binary attachment (non-filesystem).
  2873. * This method can be used to attach ascii or binary data,
  2874. * such as a BLOB record from a database.
  2875. * @param string $string String attachment data.
  2876. * @param string $filename Name of the attachment.
  2877. * @param string $encoding File encoding (see $Encoding).
  2878. * @param string $type File extension (MIME) type.
  2879. * @param string $disposition Disposition to use
  2880. * @return void
  2881. */
  2882. public function addStringAttachment(
  2883. $string,
  2884. $filename,
  2885. $encoding = 'base64',
  2886. $type = '',
  2887. $disposition = 'attachment'
  2888. ) {
  2889. // If a MIME type is not specified, try to work it out from the file name
  2890. if ($type == '') {
  2891. $type = self::filenameToType($filename);
  2892. }
  2893. // Append to $attachment array
  2894. $this->attachment[] = array(
  2895. 0 => $string,
  2896. 1 => $filename,
  2897. 2 => basename($filename),
  2898. 3 => $encoding,
  2899. 4 => $type,
  2900. 5 => true, // isStringAttachment
  2901. 6 => $disposition,
  2902. 7 => 0
  2903. );
  2904. }
  2905.  
  2906. /**
  2907. * Add an embedded (inline) attachment from a file.
  2908. * This can include images, sounds, and just about any other document type.
  2909. * These differ from 'regular' attachments in that they are intended to be
  2910. * displayed inline with the message, not just attached for download.
  2911. * This is used in HTML messages that embed the images
  2912. * the HTML refers to using the $cid value.
  2913. * @param string $path Path to the attachment.
  2914. * @param string $cid Content ID of the attachment; Use this to reference
  2915. * the content when using an embedded image in HTML.
  2916. * @param string $name Overrides the attachment name.
  2917. * @param string $encoding File encoding (see $Encoding).
  2918. * @param string $type File MIME type.
  2919. * @param string $disposition Disposition to use
  2920. * @return boolean True on successfully adding an attachment
  2921. */
  2922. public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
  2923. {
  2924. if (!@is_file($path)) {
  2925. $this->setError($this->lang('file_access') . $path);
  2926. return false;
  2927. }
  2928.  
  2929. // If a MIME type is not specified, try to work it out from the file name
  2930. if ($type == '') {
  2931. $type = self::filenameToType($path);
  2932. }
  2933.  
  2934. $filename = basename($path);
  2935. if ($name == '') {
  2936. $name = $filename;
  2937. }
  2938.  
  2939. // Append to $attachment array
  2940. $this->attachment[] = array(
  2941. 0 => $path,
  2942. 1 => $filename,
  2943. 2 => $name,
  2944. 3 => $encoding,
  2945. 4 => $type,
  2946. 5 => false, // isStringAttachment
  2947. 6 => $disposition,
  2948. 7 => $cid
  2949. );
  2950. return true;
  2951. }
  2952.  
  2953. /**
  2954. * Add an embedded stringified attachment.
  2955. * This can include images, sounds, and just about any other document type.
  2956. * Be sure to set the $type to an image type for images:
  2957. * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
  2958. * @param string $string The attachment binary data.
  2959. * @param string $cid Content ID of the attachment; Use this to reference
  2960. * the content when using an embedded image in HTML.
  2961. * @param string $name
  2962. * @param string $encoding File encoding (see $Encoding).
  2963. * @param string $type MIME type.
  2964. * @param string $disposition Disposition to use
  2965. * @return boolean True on successfully adding an attachment
  2966. */
  2967. public function addStringEmbeddedImage(
  2968. $string,
  2969. $cid,
  2970. $name = '',
  2971. $encoding = 'base64',
  2972. $type = '',
  2973. $disposition = 'inline'
  2974. ) {
  2975. // If a MIME type is not specified, try to work it out from the name
  2976. if ($type == '' and !empty($name)) {
  2977. $type = self::filenameToType($name);
  2978. }
  2979.  
  2980. // Append to $attachment array
  2981. $this->attachment[] = array(
  2982. 0 => $string,
  2983. 1 => $name,
  2984. 2 => $name,
  2985. 3 => $encoding,
  2986. 4 => $type,
  2987. 5 => true, // isStringAttachment
  2988. 6 => $disposition,
  2989. 7 => $cid
  2990. );
  2991. return true;
  2992. }
  2993.  
  2994. /**
  2995. * Check if an inline attachment is present.
  2996. * @access public
  2997. * @return boolean
  2998. */
  2999. public function inlineImageExists()
  3000. {
  3001. foreach ($this->attachment as $attachment) {
  3002. if ($attachment[6] == 'inline') {
  3003. return true;
  3004. }
  3005. }
  3006. return false;
  3007. }
  3008.  
  3009. /**
  3010. * Check if an attachment (non-inline) is present.
  3011. * @return boolean
  3012. */
  3013. public function attachmentExists()
  3014. {
  3015. foreach ($this->attachment as $attachment) {
  3016. if ($attachment[6] == 'attachment') {
  3017. return true;
  3018. }
  3019. }
  3020. return false;
  3021. }
  3022.  
  3023. /**
  3024. * Check if this message has an alternative body set.
  3025. * @return boolean
  3026. */
  3027. public function alternativeExists()
  3028. {
  3029. return !empty($this->AltBody);
  3030. }
  3031.  
  3032. /**
  3033. * Clear queued addresses of given kind.
  3034. * @access protected
  3035. * @param string $kind 'to', 'cc', or 'bcc'
  3036. * @return void
  3037. */
  3038. public function clearQueuedAddresses($kind)
  3039. {
  3040. $RecipientsQueue = $this->RecipientsQueue;
  3041. foreach ($RecipientsQueue as $address => $params) {
  3042. if ($params[0] == $kind) {
  3043. unset($this->RecipientsQueue[$address]);
  3044. }
  3045. }
  3046. }
  3047.  
  3048. /**
  3049. * Clear all To recipients.
  3050. * @return void
  3051. */
  3052. public function clearAddresses()
  3053. {
  3054. foreach ($this->to as $to) {
  3055. unset($this->all_recipients[strtolower($to[0])]);
  3056. }
  3057. $this->to = array();
  3058. $this->clearQueuedAddresses('to');
  3059. }
  3060.  
  3061. /**
  3062. * Clear all CC recipients.
  3063. * @return void
  3064. */
  3065. public function clearCCs()
  3066. {
  3067. foreach ($this->cc as $cc) {
  3068. unset($this->all_recipients[strtolower($cc[0])]);
  3069. }
  3070. $this->cc = array();
  3071. $this->clearQueuedAddresses('cc');
  3072. }
  3073.  
  3074. /**
  3075. * Clear all BCC recipients.
  3076. * @return void
  3077. */
  3078. public function clearBCCs()
  3079. {
  3080. foreach ($this->bcc as $bcc) {
  3081. unset($this->all_recipients[strtolower($bcc[0])]);
  3082. }
  3083. $this->bcc = array();
  3084. $this->clearQueuedAddresses('bcc');
  3085. }
  3086.  
  3087. /**
  3088. * Clear all ReplyTo recipients.
  3089. * @return void
  3090. */
  3091. public function clearReplyTos()
  3092. {
  3093. $this->ReplyTo = array();
  3094. $this->ReplyToQueue = array();
  3095. }
  3096.  
  3097. /**
  3098. * Clear all recipient types.
  3099. * @return void
  3100. */
  3101. public function clearAllRecipients()
  3102. {
  3103. $this->to = array();
  3104. $this->cc = array();
  3105. $this->bcc = array();
  3106. $this->all_recipients = array();
  3107. $this->RecipientsQueue = array();
  3108. }
  3109.  
  3110. /**
  3111. * Clear all filesystem, string, and binary attachments.
  3112. * @return void
  3113. */
  3114. public function clearAttachments()
  3115. {
  3116. $this->attachment = array();
  3117. }
  3118.  
  3119. /**
  3120. * Clear all custom headers.
  3121. * @return void
  3122. */
  3123. public function clearCustomHeaders()
  3124. {
  3125. $this->CustomHeader = array();
  3126. }
  3127.  
  3128. /**
  3129. * Add an error message to the error container.
  3130. * @access protected
  3131. * @param string $msg
  3132. * @return void
  3133. */
  3134. protected function setError($msg)
  3135. {
  3136. $this->error_count++;
  3137. if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  3138. $lasterror = $this->smtp->getError();
  3139. if (!empty($lasterror['error'])) {
  3140. $msg .= $this->lang('smtp_error') . $lasterror['error'];
  3141. if (!empty($lasterror['detail'])) {
  3142. $msg .= ' Detail: '. $lasterror['detail'];
  3143. }
  3144. if (!empty($lasterror['smtp_code'])) {
  3145. $msg .= ' SMTP code: ' . $lasterror['smtp_code'];
  3146. }
  3147. if (!empty($lasterror['smtp_code_ex'])) {
  3148. $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex'];
  3149. }
  3150. }
  3151. }
  3152. $this->ErrorInfo = $msg;
  3153. }
  3154.  
  3155. /**
  3156. * Return an RFC 822 formatted date.
  3157. * @access public
  3158. * @return string
  3159. * @static
  3160. */
  3161. public static function rfcDate()
  3162. {
  3163. // Set the time zone to whatever the default is to avoid 500 errors
  3164. // Will default to UTC if it's not set properly in php.ini
  3165. date_default_timezone_set(@date_default_timezone_get());
  3166. return date('D, j M Y H:i:s O');
  3167. }
  3168.  
  3169. /**
  3170. * Get the server hostname.
  3171. * Returns 'localhost.localdomain' if unknown.
  3172. * @access protected
  3173. * @return string
  3174. */
  3175. protected function serverHostname()
  3176. {
  3177. $result = 'localhost.localdomain';
  3178. if (!empty($this->Hostname)) {
  3179. $result = $this->Hostname;
  3180. } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) {
  3181. $result = $_SERVER['SERVER_NAME'];
  3182. } elseif (function_exists('gethostname') && gethostname() !== false) {
  3183. $result = gethostname();
  3184. } elseif (php_uname('n') !== false) {
  3185. $result = php_uname('n');
  3186. }
  3187. return $result;
  3188. }
  3189.  
  3190. /**
  3191. * Get an error message in the current language.
  3192. * @access protected
  3193. * @param string $key
  3194. * @return string
  3195. */
  3196. protected function lang($key)
  3197. {
  3198. if (count($this->language) < 1) {
  3199. $this->setLanguage('en'); // set the default language
  3200. }
  3201.  
  3202. if (array_key_exists($key, $this->language)) {
  3203. if ($key == 'smtp_connect_failed') {
  3204. //Include a link to troubleshooting docs on SMTP connection failure
  3205. //this is by far the biggest cause of support questions
  3206. //but it's usually not PHPMailer's fault.
  3207. return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
  3208. }
  3209. return $this->language[$key];
  3210. } else {
  3211. //Return the key as a fallback
  3212. return $key;
  3213. }
  3214. }
  3215.  
  3216. /**
  3217. * Check if an error occurred.
  3218. * @access public
  3219. * @return boolean True if an error did occur.
  3220. */
  3221. public function isError()
  3222. {
  3223. return ($this->error_count > 0);
  3224. }
  3225.  
  3226. /**
  3227. * Ensure consistent line endings in a string.
  3228. * Changes every end of line from CRLF, CR or LF to $this->LE.
  3229. * @access public
  3230. * @param string $str String to fixEOL
  3231. * @return string
  3232. */
  3233. public function fixEOL($str)
  3234. {
  3235. // Normalise to \n
  3236. $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
  3237. // Now convert LE as needed
  3238. if ($this->LE !== "\n") {
  3239. $nstr = str_replace("\n", $this->LE, $nstr);
  3240. }
  3241. return $nstr;
  3242. }
  3243.  
  3244. /**
  3245. * Add a custom header.
  3246. * $name value can be overloaded to contain
  3247. * both header name and value (name:value)
  3248. * @access public
  3249. * @param string $name Custom header name
  3250. * @param string $value Header value
  3251. * @return void
  3252. */
  3253. public function addCustomHeader($name, $value = null)
  3254. {
  3255. if ($value === null) {
  3256. // Value passed in as name:value
  3257. $this->CustomHeader[] = explode(':', $name, 2);
  3258. } else {
  3259. $this->CustomHeader[] = array($name, $value);
  3260. }
  3261. }
  3262.  
  3263. /**
  3264. * Returns all custom headers.
  3265. * @return array
  3266. */
  3267. public function getCustomHeaders()
  3268. {
  3269. return $this->CustomHeader;
  3270. }
  3271.  
  3272. /**
  3273. * Create a message from an HTML string.
  3274. * Automatically makes modifications for inline images and backgrounds
  3275. * and creates a plain-text version by converting the HTML.
  3276. * Overwrites any existing values in $this->Body and $this->AltBody
  3277. * @access public
  3278. * @param string $message HTML message string
  3279. * @param string $basedir baseline directory for path
  3280. * @param boolean|callable $advanced Whether to use the internal HTML to text converter
  3281. * or your own custom converter @see PHPMailer::html2text()
  3282. * @return string $message
  3283. */
  3284. public function msgHTML($message, $basedir = '', $advanced = false)
  3285. {
  3286. preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
  3287. if (array_key_exists(2, $images)) {
  3288. foreach ($images[2] as $imgindex => $url) {
  3289. // Convert data URIs into embedded images
  3290. if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) {
  3291. $data = substr($url, strpos($url, ','));
  3292. if ($match[2]) {
  3293. $data = base64_decode($data);
  3294. } else {
  3295. $data = rawurldecode($data);
  3296. }
  3297. $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
  3298. if ($this->addStringEmbeddedImage($data, $cid, 'embed' . $imgindex, 'base64', $match[1])) {
  3299. $message = str_replace(
  3300. $images[0][$imgindex],
  3301. $images[1][$imgindex] . '="cid:' . $cid . '"',
  3302. $message
  3303. );
  3304. }
  3305. } elseif (substr($url, 0, 4) !== 'cid:' && !preg_match('#^[A-z]+://#', $url)) {
  3306. // Do not change urls for absolute images (thanks to corvuscorax)
  3307. // Do not change urls that are already inline images
  3308. $filename = basename($url);
  3309. $directory = dirname($url);
  3310. if ($directory == '.') {
  3311. $directory = '';
  3312. }
  3313. $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
  3314. if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
  3315. $basedir .= '/';
  3316. }
  3317. if (strlen($directory) > 1 && substr($directory, -1) != '/') {
  3318. $directory .= '/';
  3319. }
  3320. if ($this->addEmbeddedImage(
  3321. $basedir . $directory . $filename,
  3322. $cid,
  3323. $filename,
  3324. 'base64',
  3325. self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION))
  3326. )
  3327. ) {
  3328. $message = preg_replace(
  3329. '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
  3330. $images[1][$imgindex] . '="cid:' . $cid . '"',
  3331. $message
  3332. );
  3333. }
  3334. }
  3335. }
  3336. }
  3337. $this->isHTML(true);
  3338. // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
  3339. $this->Body = $this->normalizeBreaks($message);
  3340. $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
  3341. if (empty($this->AltBody)) {
  3342. $this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
  3343. self::CRLF . self::CRLF;
  3344. }
  3345. return $this->Body;
  3346. }
  3347.  
  3348. /**
  3349. * Convert an HTML string into plain text.
  3350. * This is used by msgHTML().
  3351. * Note - older versions of this function used a bundled advanced converter
  3352. * which was been removed for license reasons in #232
  3353. * Example usage:
  3354. * <code>
  3355. * // Use default conversion
  3356. * $plain = $mail->html2text($html);
  3357. * // Use your own custom converter
  3358. * $plain = $mail->html2text($html, function($html) {
  3359. * $converter = new MyHtml2text($html);
  3360. * return $converter->get_text();
  3361. * });
  3362. * </code>
  3363. * @param string $html The HTML text to convert
  3364. * @param boolean|callable $advanced Any boolean value to use the internal converter,
  3365. * or provide your own callable for custom conversion.
  3366. * @return string
  3367. */
  3368. public function html2text($html, $advanced = false)
  3369. {
  3370. if (is_callable($advanced)) {
  3371. return call_user_func($advanced, $html);
  3372. }
  3373. return html_entity_decode(
  3374. trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
  3375. ENT_QUOTES,
  3376. $this->CharSet
  3377. );
  3378. }
  3379.  
  3380. /**
  3381. * Get the MIME type for a file extension.
  3382. * @param string $ext File extension
  3383. * @access public
  3384. * @return string MIME type of file.
  3385. * @static
  3386. */
  3387. public static function _mime_types($ext = '')
  3388. {
  3389. $mimes = array(
  3390. 'xl' => 'application/excel',
  3391. 'js' => 'application/javascript',
  3392. 'hqx' => 'application/mac-binhex40',
  3393. 'cpt' => 'application/mac-compactpro',
  3394. 'bin' => 'application/macbinary',
  3395. 'doc' => 'application/msword',
  3396. 'word' => 'application/msword',
  3397. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  3398. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  3399. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  3400. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  3401. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  3402. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  3403. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  3404. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  3405. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  3406. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  3407. 'class' => 'application/octet-stream',
  3408. 'dll' => 'application/octet-stream',
  3409. 'dms' => 'application/octet-stream',
  3410. 'exe' => 'application/octet-stream',
  3411. 'lha' => 'application/octet-stream',
  3412. 'lzh' => 'application/octet-stream',
  3413. 'psd' => 'application/octet-stream',
  3414. 'sea' => 'application/octet-stream',
  3415. 'so' => 'application/octet-stream',
  3416. 'oda' => 'application/oda',
  3417. 'pdf' => 'application/pdf',
  3418. 'ai' => 'application/postscript',
  3419. 'eps' => 'application/postscript',
  3420. 'ps' => 'application/postscript',
  3421. 'smi' => 'application/smil',
  3422. 'smil' => 'application/smil',
  3423. 'mif' => 'application/vnd.mif',
  3424. 'xls' => 'application/vnd.ms-excel',
  3425. 'ppt' => 'application/vnd.ms-powerpoint',
  3426. 'wbxml' => 'application/vnd.wap.wbxml',
  3427. 'wmlc' => 'application/vnd.wap.wmlc',
  3428. 'dcr' => 'application/x-director',
  3429. 'dir' => 'application/x-director',
  3430. 'dxr' => 'application/x-director',
  3431. 'dvi' => 'application/x-dvi',
  3432. 'gtar' => 'application/x-gtar',
  3433. 'php3' => 'application/x-httpd-php',
  3434. 'php4' => 'application/x-httpd-php',
  3435. 'php' => 'application/x-httpd-php',
  3436. 'phtml' => 'application/x-httpd-php',
  3437. 'phps' => 'application/x-httpd-php-source',
  3438. 'swf' => 'application/x-shockwave-flash',
  3439. 'sit' => 'application/x-stuffit',
  3440. 'tar' => 'application/x-tar',
  3441. 'tgz' => 'application/x-tar',
  3442. 'xht' => 'application/xhtml+xml',
  3443. 'xhtml' => 'application/xhtml+xml',
  3444. 'zip' => 'application/zip',
  3445. 'mid' => 'audio/midi',
  3446. 'midi' => 'audio/midi',
  3447. 'mp2' => 'audio/mpeg',
  3448. 'mp3' => 'audio/mpeg',
  3449. 'mpga' => 'audio/mpeg',
  3450. 'aif' => 'audio/x-aiff',
  3451. 'aifc' => 'audio/x-aiff',
  3452. 'aiff' => 'audio/x-aiff',
  3453. 'ram' => 'audio/x-pn-realaudio',
  3454. 'rm' => 'audio/x-pn-realaudio',
  3455. 'rpm' => 'audio/x-pn-realaudio-plugin',
  3456. 'ra' => 'audio/x-realaudio',
  3457. 'wav' => 'audio/x-wav',
  3458. 'bmp' => 'image/bmp',
  3459. 'gif' => 'image/gif',
  3460. 'jpeg' => 'image/jpeg',
  3461. 'jpe' => 'image/jpeg',
  3462. 'jpg' => 'image/jpeg',
  3463. 'png' => 'image/png',
  3464. 'tiff' => 'image/tiff',
  3465. 'tif' => 'image/tiff',
  3466. 'eml' => 'message/rfc822',
  3467. 'css' => 'text/css',
  3468. 'html' => 'text/html',
  3469. 'htm' => 'text/html',
  3470. 'shtml' => 'text/html',
  3471. 'log' => 'text/plain',
  3472. 'text' => 'text/plain',
  3473. 'txt' => 'text/plain',
  3474. 'rtx' => 'text/richtext',
  3475. 'rtf' => 'text/rtf',
  3476. 'vcf' => 'text/vcard',
  3477. 'vcard' => 'text/vcard',
  3478. 'xml' => 'text/xml',
  3479. 'xsl' => 'text/xml',
  3480. 'mpeg' => 'video/mpeg',
  3481. 'mpe' => 'video/mpeg',
  3482. 'mpg' => 'video/mpeg',
  3483. 'mov' => 'video/quicktime',
  3484. 'qt' => 'video/quicktime',
  3485. 'rv' => 'video/vnd.rn-realvideo',
  3486. 'avi' => 'video/x-msvideo',
  3487. 'movie' => 'video/x-sgi-movie'
  3488. );
  3489. if (array_key_exists(strtolower($ext), $mimes)) {
  3490. return $mimes[strtolower($ext)];
  3491. }
  3492. return 'application/octet-stream';
  3493. }
  3494.  
  3495. /**
  3496. * Map a file name to a MIME type.
  3497. * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
  3498. * @param string $filename A file name or full path, does not need to exist as a file
  3499. * @return string
  3500. * @static
  3501. */
  3502. public static function filenameToType($filename)
  3503. {
  3504. // In case the path is a URL, strip any query string before getting extension
  3505. $qpos = strpos($filename, '?');
  3506. if (false !== $qpos) {
  3507. $filename = substr($filename, 0, $qpos);
  3508. }
  3509. $pathinfo = self::mb_pathinfo($filename);
  3510. return self::_mime_types($pathinfo['extension']);
  3511. }
  3512.  
  3513. /**
  3514. * Multi-byte-safe pathinfo replacement.
  3515. * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe.
  3516. * Works similarly to the one in PHP >= 5.2.0
  3517. * @link http://www.php.net/manual/en/function.pathinfo.php#107461
  3518. * @param string $path A filename or path, does not need to exist as a file
  3519. * @param integer|string $options Either a PATHINFO_* constant,
  3520. * or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2
  3521. * @return string|array
  3522. * @static
  3523. */
  3524. public static function mb_pathinfo($path, $options = null)
  3525. {
  3526. $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
  3527. $pathinfo = array();
  3528. if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) {
  3529. if (array_key_exists(1, $pathinfo)) {
  3530. $ret['dirname'] = $pathinfo[1];
  3531. }
  3532. if (array_key_exists(2, $pathinfo)) {
  3533. $ret['basename'] = $pathinfo[2];
  3534. }
  3535. if (array_key_exists(5, $pathinfo)) {
  3536. $ret['extension'] = $pathinfo[5];
  3537. }
  3538. if (array_key_exists(3, $pathinfo)) {
  3539. $ret['filename'] = $pathinfo[3];
  3540. }
  3541. }
  3542. switch ($options) {
  3543. case PATHINFO_DIRNAME:
  3544. case 'dirname':
  3545. return $ret['dirname'];
  3546. case PATHINFO_BASENAME:
  3547. case 'basename':
  3548. return $ret['basename'];
  3549. case PATHINFO_EXTENSION:
  3550. case 'extension':
  3551. return $ret['extension'];
  3552. case PATHINFO_FILENAME:
  3553. case 'filename':
  3554. return $ret['filename'];
  3555. default:
  3556. return $ret;
  3557. }
  3558. }
  3559.  
  3560. /**
  3561. * Set or reset instance properties.
  3562. * You should avoid this function - it's more verbose, less efficient, more error-prone and
  3563. * harder to debug than setting properties directly.
  3564. * Usage Example:
  3565. * `$mail->set('SMTPSecure', 'tls');`
  3566. * is the same as:
  3567. * `$mail->SMTPSecure = 'tls';`
  3568. * @access public
  3569. * @param string $name The property name to set
  3570. * @param mixed $value The value to set the property to
  3571. * @return boolean
  3572. * @TODO Should this not be using the __set() magic function?
  3573. */
  3574. public function set($name, $value = '')
  3575. {
  3576. if (property_exists($this, $name)) {
  3577. $this->$name = $value;
  3578. return true;
  3579. } else {
  3580. $this->setError($this->lang('variable_set') . $name);
  3581. return false;
  3582. }
  3583. }
  3584.  
  3585. /**
  3586. * Strip newlines to prevent header injection.
  3587. * @access public
  3588. * @param string $str
  3589. * @return string
  3590. */
  3591. public function secureHeader($str)
  3592. {
  3593. return trim(str_replace(array("\r", "\n"), '', $str));
  3594. }
  3595.  
  3596. /**
  3597. * Normalize line breaks in a string.
  3598. * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
  3599. * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
  3600. * @param string $text
  3601. * @param string $breaktype What kind of line break to use, defaults to CRLF
  3602. * @return string
  3603. * @access public
  3604. * @static
  3605. */
  3606. public static function normalizeBreaks($text, $breaktype = "\r\n")
  3607. {
  3608. return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
  3609. }
  3610.  
  3611. /**
  3612. * Set the public and private key files and password for S/MIME signing.
  3613. * @access public
  3614. * @param string $cert_filename
  3615. * @param string $key_filename
  3616. * @param string $key_pass Password for private key
  3617. * @param string $extracerts_filename Optional path to chain certificate
  3618. */
  3619. public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
  3620. {
  3621. $this->sign_cert_file = $cert_filename;
  3622. $this->sign_key_file = $key_filename;
  3623. $this->sign_key_pass = $key_pass;
  3624. $this->sign_extracerts_file = $extracerts_filename;
  3625. }
  3626.  
  3627. /**
  3628. * Quoted-Printable-encode a DKIM header.
  3629. * @access public
  3630. * @param string $txt
  3631. * @return string
  3632. */
  3633. public function DKIM_QP($txt)
  3634. {
  3635. $line = '';
  3636. for ($i = 0; $i < strlen($txt); $i++) {
  3637. $ord = ord($txt[$i]);
  3638. if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
  3639. $line .= $txt[$i];
  3640. } else {
  3641. $line .= '=' . sprintf('%02X', $ord);
  3642. }
  3643. }
  3644. return $line;
  3645. }
  3646.  
  3647. /**
  3648. * Generate a DKIM signature.
  3649. * @access public
  3650. * @param string $signHeader
  3651. * @throws phpmailerException
  3652. * @return string
  3653. */
  3654. public function DKIM_Sign($signHeader)
  3655. {
  3656. if (!defined('PKCS7_TEXT')) {
  3657. if ($this->exceptions) {
  3658. throw new phpmailerException($this->lang('extension_missing') . 'openssl');
  3659. }
  3660. return '';
  3661. }
  3662. $privKeyStr = file_get_contents($this->DKIM_private);
  3663. if ($this->DKIM_passphrase != '') {
  3664. $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  3665. } else {
  3666. $privKey = $privKeyStr;
  3667. }
  3668. if (openssl_sign($signHeader, $signature, $privKey)) {
  3669. return base64_encode($signature);
  3670. }
  3671. return '';
  3672. }
  3673.  
  3674. /**
  3675. * Generate a DKIM canonicalization header.
  3676. * @access public
  3677. * @param string $signHeader Header
  3678. * @return string
  3679. */
  3680. public function DKIM_HeaderC($signHeader)
  3681. {
  3682. $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader);
  3683. $lines = explode("\r\n", $signHeader);
  3684. foreach ($lines as $key => $line) {
  3685. list($heading, $value) = explode(':', $line, 2);
  3686. $heading = strtolower($heading);
  3687. $value = preg_replace('/\s+/', ' ', $value); // Compress useless spaces
  3688. $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value
  3689. }
  3690. $signHeader = implode("\r\n", $lines);
  3691. return $signHeader;
  3692. }
  3693.  
  3694. /**
  3695. * Generate a DKIM canonicalization body.
  3696. * @access public
  3697. * @param string $body Message Body
  3698. * @return string
  3699. */
  3700. public function DKIM_BodyC($body)
  3701. {
  3702. if ($body == '') {
  3703. return "\r\n";
  3704. }
  3705. // stabilize line endings
  3706. $body = str_replace("\r\n", "\n", $body);
  3707. $body = str_replace("\n", "\r\n", $body);
  3708. // END stabilize line endings
  3709. while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
  3710. $body = substr($body, 0, strlen($body) - 2);
  3711. }
  3712. return $body;
  3713. }
  3714.  
  3715. /**
  3716. * Create the DKIM header and body in a new message header.
  3717. * @access public
  3718. * @param string $headers_line Header lines
  3719. * @param string $subject Subject
  3720. * @param string $body Body
  3721. * @return string
  3722. */
  3723. public function DKIM_Add($headers_line, $subject, $body)
  3724. {
  3725. $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
  3726. $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  3727. $DKIMquery = 'dns/txt'; // Query method
  3728. $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  3729. $subject_header = "Subject: $subject";
  3730. $headers = explode($this->LE, $headers_line);
  3731. $from_header = '';
  3732. $to_header = '';
  3733. $current = '';
  3734. foreach ($headers as $header) {
  3735. if (strpos($header, 'From:') === 0) {
  3736. $from_header = $header;
  3737. $current = 'from_header';
  3738. } elseif (strpos($header, 'To:') === 0) {
  3739. $to_header = $header;
  3740. $current = 'to_header';
  3741. } else {
  3742. if (!empty($$current) && strpos($header, ' =?') === 0) {
  3743. $$current .= $header;
  3744. } else {
  3745. $current = '';
  3746. }
  3747. }
  3748. }
  3749. $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  3750. $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  3751. $subject = str_replace(
  3752. '|',
  3753. '=7C',
  3754. $this->DKIM_QP($subject_header)
  3755. ); // Copied header fields (dkim-quoted-printable)
  3756. $body = $this->DKIM_BodyC($body);
  3757. $DKIMlen = strlen($body); // Length of body
  3758. $DKIMb64 = base64_encode(pack('H*', sha1($body))); // Base64 of packed binary SHA-1 hash of body
  3759. if ('' == $this->DKIM_identity) {
  3760. $ident = '';
  3761. } else {
  3762. $ident = ' i=' . $this->DKIM_identity . ';';
  3763. }
  3764. $dkimhdrs = 'DKIM-Signature: v=1; a=' .
  3765. $DKIMsignatureType . '; q=' .
  3766. $DKIMquery . '; l=' .
  3767. $DKIMlen . '; s=' .
  3768. $this->DKIM_selector .
  3769. ";\r\n" .
  3770. "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
  3771. "\th=From:To:Subject;\r\n" .
  3772. "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
  3773. "\tz=$from\r\n" .
  3774. "\t|$to\r\n" .
  3775. "\t|$subject;\r\n" .
  3776. "\tbh=" . $DKIMb64 . ";\r\n" .
  3777. "\tb=";
  3778. $toSign = $this->DKIM_HeaderC(
  3779. $from_header . "\r\n" .
  3780. $to_header . "\r\n" .
  3781. $subject_header . "\r\n" .
  3782. $dkimhdrs
  3783. );
  3784. $signed = $this->DKIM_Sign($toSign);
  3785. return $dkimhdrs . $signed . "\r\n";
  3786. }
  3787.  
  3788. /**
  3789. * Detect if a string contains a line longer than the maximum line length allowed.
  3790. * @param string $str
  3791. * @return boolean
  3792. * @static
  3793. */
  3794. public static function hasLineLongerThanMax($str)
  3795. {
  3796. //+2 to include CRLF line break for a 1000 total
  3797. return (boolean)preg_match('/^(.{'.(self::MAX_LINE_LENGTH + 2).',})/m', $str);
  3798. }
  3799.  
  3800. /**
  3801. * Allows for public read access to 'to' property.
  3802. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  3803. * @access public
  3804. * @return array
  3805. */
  3806. public function getToAddresses()
  3807. {
  3808. return $this->to;
  3809. }
  3810.  
  3811. /**
  3812. * Allows for public read access to 'cc' property.
  3813. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  3814. * @access public
  3815. * @return array
  3816. */
  3817. public function getCcAddresses()
  3818. {
  3819. return $this->cc;
  3820. }
  3821.  
  3822. /**
  3823. * Allows for public read access to 'bcc' property.
  3824. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  3825. * @access public
  3826. * @return array
  3827. */
  3828. public function getBccAddresses()
  3829. {
  3830. return $this->bcc;
  3831. }
  3832.  
  3833. /**
  3834. * Allows for public read access to 'ReplyTo' property.
  3835. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  3836. * @access public
  3837. * @return array
  3838. */
  3839. public function getReplyToAddresses()
  3840. {
  3841. return $this->ReplyTo;
  3842. }
  3843.  
  3844. /**
  3845. * Allows for public read access to 'all_recipients' property.
  3846. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included.
  3847. * @access public
  3848. * @return array
  3849. */
  3850. public function getAllRecipientAddresses()
  3851. {
  3852. return $this->all_recipients;
  3853. }
  3854.  
  3855. /**
  3856. * Perform a callback.
  3857. * @param boolean $isSent
  3858. * @param array $to
  3859. * @param array $cc
  3860. * @param array $bcc
  3861. * @param string $subject
  3862. * @param string $body
  3863. * @param string $from
  3864. */
  3865. protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from)
  3866. {
  3867. if (!empty($this->action_function) && is_callable($this->action_function)) {
  3868. $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
  3869. call_user_func_array($this->action_function, $params);
  3870. }
  3871. }
  3872. }
  3873.  
  3874. /**
  3875. * PHPMailer exception handler
  3876. * @package PHPMailer
  3877. */
  3878. class phpmailerException extends Exception
  3879. {
  3880. /**
  3881. * Prettify error message output
  3882. * @return string
  3883. */
  3884. public function errorMessage()
  3885. {
  3886. $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  3887. return $errorMsg;
  3888. }
  3889. }
  3890.  
  3891. /**
  3892. * PHPMailer RFC821 SMTP email transport class.
  3893. * PHP Version 5
  3894. * @package PHPMailer
  3895. * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
  3896. * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  3897. * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  3898. * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  3899. * @author Brent R. Matzelle (original founder)
  3900. * @copyright 2014 Marcus Bointon
  3901. * @copyright 2010 - 2012 Jim Jagielski
  3902. * @copyright 2004 - 2009 Andy Prevost
  3903. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  3904. * @note This program is distributed in the hope that it will be useful - WITHOUT
  3905. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  3906. * FITNESS FOR A PARTICULAR PURPOSE.
  3907. */
  3908.  
  3909. /**
  3910. * PHPMailer RFC821 SMTP email transport class.
  3911. * Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server.
  3912. * @package PHPMailer
  3913. * @author Chris Ryan
  3914. * @author Marcus Bointon <phpmailer@synchromedia.co.uk>
  3915. */
  3916. class SMTP
  3917. {
  3918. /**
  3919. * The PHPMailer SMTP version number.
  3920. * @var string
  3921. */
  3922. const VERSION = '5.2.14';
  3923.  
  3924. /**
  3925. * SMTP line break constant.
  3926. * @var string
  3927. */
  3928. const CRLF = "\r\n";
  3929.  
  3930. /**
  3931. * The SMTP port to use if one is not specified.
  3932. * @var integer
  3933. */
  3934. const DEFAULT_SMTP_PORT = 25;
  3935.  
  3936. /**
  3937. * The maximum line length allowed by RFC 2822 section 2.1.1
  3938. * @var integer
  3939. */
  3940. const MAX_LINE_LENGTH = 998;
  3941.  
  3942. /**
  3943. * Debug level for no output
  3944. */
  3945. const DEBUG_OFF = 0;
  3946.  
  3947. /**
  3948. * Debug level to show client -> server messages
  3949. */
  3950. const DEBUG_CLIENT = 1;
  3951.  
  3952. /**
  3953. * Debug level to show client -> server and server -> client messages
  3954. */
  3955. const DEBUG_SERVER = 2;
  3956.  
  3957. /**
  3958. * Debug level to show connection status, client -> server and server -> client messages
  3959. */
  3960. const DEBUG_CONNECTION = 3;
  3961.  
  3962. /**
  3963. * Debug level to show all messages
  3964. */
  3965. const DEBUG_LOWLEVEL = 4;
  3966.  
  3967. /**
  3968. * The PHPMailer SMTP Version number.
  3969. * @var string
  3970. * @deprecated Use the `VERSION` constant instead
  3971. * @see SMTP::VERSION
  3972. */
  3973. public $Version = '5.2.14';
  3974.  
  3975. /**
  3976. * SMTP server port number.
  3977. * @var integer
  3978. * @deprecated This is only ever used as a default value, so use the `DEFAULT_SMTP_PORT` constant instead
  3979. * @see SMTP::DEFAULT_SMTP_PORT
  3980. */
  3981. public $SMTP_PORT = 25;
  3982.  
  3983. /**
  3984. * SMTP reply line ending.
  3985. * @var string
  3986. * @deprecated Use the `CRLF` constant instead
  3987. * @see SMTP::CRLF
  3988. */
  3989. public $CRLF = "\r\n";
  3990.  
  3991. /**
  3992. * Debug output level.
  3993. * Options:
  3994. * * self::DEBUG_OFF (`0`) No debug output, default
  3995. * * self::DEBUG_CLIENT (`1`) Client commands
  3996. * * self::DEBUG_SERVER (`2`) Client commands and server responses
  3997. * * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status
  3998. * * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages
  3999. * @var integer
  4000. */
  4001. public $do_debug = self::DEBUG_OFF;
  4002.  
  4003. /**
  4004. * How to handle debug output.
  4005. * Options:
  4006. * * `echo` Output plain-text as-is, appropriate for CLI
  4007. * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
  4008. * * `error_log` Output to error log as configured in php.ini
  4009. *
  4010. * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
  4011. * <code>
  4012. * $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
  4013. * </code>
  4014. * @var string|callable
  4015. */
  4016. public $Debugoutput = 'echo';
  4017.  
  4018. /**
  4019. * Whether to use VERP.
  4020. * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
  4021. * @link http://www.postfix.org/VERP_README.html Info on VERP
  4022. * @var boolean
  4023. */
  4024. public $do_verp = false;
  4025.  
  4026. /**
  4027. * The timeout value for connection, in seconds.
  4028. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
  4029. * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure.
  4030. * @link http://tools.ietf.org/html/rfc2821#section-4.5.3.2
  4031. * @var integer
  4032. */
  4033. public $Timeout = 300;
  4034.  
  4035. /**
  4036. * How long to wait for commands to complete, in seconds.
  4037. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
  4038. * @var integer
  4039. */
  4040. public $Timelimit = 300;
  4041.  
  4042. /**
  4043. * The socket for the server connection.
  4044. * @var resource
  4045. */
  4046. protected $smtp_conn;
  4047.  
  4048. /**
  4049. * Error information, if any, for the last SMTP command.
  4050. * @var array
  4051. */
  4052. protected $error = array(
  4053. 'error' => '',
  4054. 'detail' => '',
  4055. 'smtp_code' => '',
  4056. 'smtp_code_ex' => ''
  4057. );
  4058.  
  4059. /**
  4060. * The reply the server sent to us for HELO.
  4061. * If null, no HELO string has yet been received.
  4062. * @var string|null
  4063. */
  4064. protected $helo_rply = null;
  4065.  
  4066. /**
  4067. * The set of SMTP extensions sent in reply to EHLO command.
  4068. * Indexes of the array are extension names.
  4069. * Value at index 'HELO' or 'EHLO' (according to command that was sent)
  4070. * represents the server name. In case of HELO it is the only element of the array.
  4071. * Other values can be boolean TRUE or an array containing extension options.
  4072. * If null, no HELO/EHLO string has yet been received.
  4073. * @var array|null
  4074. */
  4075. protected $server_caps = null;
  4076.  
  4077. /**
  4078. * The most recent reply received from the server.
  4079. * @var string
  4080. */
  4081. protected $last_reply = '';
  4082.  
  4083. /**
  4084. * Output debugging info via a user-selected method.
  4085. * @see SMTP::$Debugoutput
  4086. * @see SMTP::$do_debug
  4087. * @param string $str Debug string to output
  4088. * @param integer $level The debug level of this message; see DEBUG_* constants
  4089. * @return void
  4090. */
  4091. protected function edebug($str, $level = 0)
  4092. {
  4093. if ($level > $this->do_debug) {
  4094. return;
  4095. }
  4096. //Avoid clash with built-in function names
  4097. if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
  4098. call_user_func($this->Debugoutput, $str, $this->do_debug);
  4099. return;
  4100. }
  4101. switch ($this->Debugoutput) {
  4102. case 'error_log':
  4103. //Don't output, just log
  4104. error_log($str);
  4105. break;
  4106. case 'html':
  4107. //Cleans up output a bit for a better looking, HTML-safe output
  4108. echo htmlentities(
  4109. preg_replace('/[\r\n]+/', '', $str),
  4110. ENT_QUOTES,
  4111. 'UTF-8'
  4112. )
  4113. . "<br>\n";
  4114. break;
  4115. case 'echo':
  4116. default:
  4117. //Normalize line breaks
  4118. $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
  4119. echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
  4120. "\n",
  4121. "\n \t ",
  4122. trim($str)
  4123. )."\n";
  4124. }
  4125. }
  4126.  
  4127. /**
  4128. * Connect to an SMTP server.
  4129. * @param string $host SMTP server IP or host name
  4130. * @param integer $port The port number to connect to
  4131. * @param integer $timeout How long to wait for the connection to open
  4132. * @param array $options An array of options for stream_context_create()
  4133. * @access public
  4134. * @return boolean
  4135. */
  4136. public function connect($host, $port = null, $timeout = 30, $options = array())
  4137. {
  4138. static $streamok;
  4139. //This is enabled by default since 5.0.0 but some providers disable it
  4140. //Check this once and cache the result
  4141. if (is_null($streamok)) {
  4142. $streamok = function_exists('stream_socket_client');
  4143. }
  4144. // Clear errors to avoid confusion
  4145. $this->setError('');
  4146. // Make sure we are __not__ connected
  4147. if ($this->connected()) {
  4148. // Already connected, generate error
  4149. $this->setError('Already connected to a server');
  4150. return false;
  4151. }
  4152. if (empty($port)) {
  4153. $port = self::DEFAULT_SMTP_PORT;
  4154. }
  4155. // Connect to the SMTP server
  4156. $this->edebug(
  4157. "Connection: opening to $host:$port, timeout=$timeout, options=".var_export($options, true),
  4158. self::DEBUG_CONNECTION
  4159. );
  4160. $errno = 0;
  4161. $errstr = '';
  4162. if ($streamok) {
  4163. $socket_context = stream_context_create($options);
  4164. //Suppress errors; connection failures are handled at a higher level
  4165. $this->smtp_conn = @stream_socket_client(
  4166. $host . ":" . $port,
  4167. $errno,
  4168. $errstr,
  4169. $timeout,
  4170. STREAM_CLIENT_CONNECT,
  4171. $socket_context
  4172. );
  4173. } else {
  4174. //Fall back to fsockopen which should work in more places, but is missing some features
  4175. $this->edebug(
  4176. "Connection: stream_socket_client not available, falling back to fsockopen",
  4177. self::DEBUG_CONNECTION
  4178. );
  4179. $this->smtp_conn = fsockopen(
  4180. $host,
  4181. $port,
  4182. $errno,
  4183. $errstr,
  4184. $timeout
  4185. );
  4186. }
  4187. // Verify we connected properly
  4188. if (!is_resource($this->smtp_conn)) {
  4189. $this->setError(
  4190. 'Failed to connect to server',
  4191. $errno,
  4192. $errstr
  4193. );
  4194. $this->edebug(
  4195. 'SMTP ERROR: ' . $this->error['error']
  4196. . ": $errstr ($errno)",
  4197. self::DEBUG_CLIENT
  4198. );
  4199. return false;
  4200. }
  4201. $this->edebug('Connection: opened', self::DEBUG_CONNECTION);
  4202. // SMTP server can take longer to respond, give longer timeout for first read
  4203. // Windows does not have support for this timeout function
  4204. if (substr(PHP_OS, 0, 3) != 'WIN') {
  4205. $max = ini_get('max_execution_time');
  4206. // Don't bother if unlimited
  4207. if ($max != 0 && $timeout > $max) {
  4208. @set_time_limit($timeout);
  4209. }
  4210. stream_set_timeout($this->smtp_conn, $timeout, 0);
  4211. }
  4212. // Get any announcement
  4213. $announce = $this->get_lines();
  4214. $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER);
  4215. return true;
  4216. }
  4217.  
  4218. /**
  4219. * Initiate a TLS (encrypted) session.
  4220. * @access public
  4221. * @return boolean
  4222. */
  4223. public function startTLS()
  4224. {
  4225. if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
  4226. return false;
  4227. }
  4228. // Begin encrypted connection
  4229. if (!stream_socket_enable_crypto(
  4230. $this->smtp_conn,
  4231. true,
  4232. STREAM_CRYPTO_METHOD_TLS_CLIENT
  4233. )) {
  4234. return false;
  4235. }
  4236. return true;
  4237. }
  4238.  
  4239. /**
  4240. * Perform SMTP authentication.
  4241. * Must be run after hello().
  4242. * @see hello()
  4243. * @param string $username The user name
  4244. * @param string $password The password
  4245. * @param string $authtype The auth type (PLAIN, LOGIN, NTLM, CRAM-MD5, XOAUTH2)
  4246. * @param string $realm The auth realm for NTLM
  4247. * @param string $workstation The auth workstation for NTLM
  4248. * @param null|OAuth $OAuth An optional OAuth instance (@see PHPMailerOAuth)
  4249. * @return bool True if successfully authenticated.* @access public
  4250. */
  4251. public function authenticate(
  4252. $username,
  4253. $password,
  4254. $authtype = null,
  4255. $realm = '',
  4256. $workstation = '',
  4257. $OAuth = null
  4258. ) {
  4259. if (!$this->server_caps) {
  4260. $this->setError('Authentication is not allowed before HELO/EHLO');
  4261. return false;
  4262. }
  4263.  
  4264. if (array_key_exists('EHLO', $this->server_caps)) {
  4265. // SMTP extensions are available. Let's try to find a proper authentication method
  4266.  
  4267. if (!array_key_exists('AUTH', $this->server_caps)) {
  4268. $this->setError('Authentication is not allowed at this stage');
  4269. // 'at this stage' means that auth may be allowed after the stage changes
  4270. // e.g. after STARTTLS
  4271. return false;
  4272. }
  4273.  
  4274. self::edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNKNOWN'), self::DEBUG_LOWLEVEL);
  4275. self::edebug(
  4276. 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']),
  4277. self::DEBUG_LOWLEVEL
  4278. );
  4279.  
  4280. if (empty($authtype)) {
  4281. foreach (array('LOGIN', 'CRAM-MD5', 'NTLM', 'PLAIN', 'XOAUTH2') as $method) {
  4282. if (in_array($method, $this->server_caps['AUTH'])) {
  4283. $authtype = $method;
  4284. break;
  4285. }
  4286. }
  4287. if (empty($authtype)) {
  4288. $this->setError('No supported authentication methods found');
  4289. return false;
  4290. }
  4291. self::edebug('Auth method selected: '.$authtype, self::DEBUG_LOWLEVEL);
  4292. }
  4293.  
  4294. if (!in_array($authtype, $this->server_caps['AUTH'])) {
  4295. $this->setError("The requested authentication method \"$authtype\" is not supported by the server");
  4296. return false;
  4297. }
  4298. } elseif (empty($authtype)) {
  4299. $authtype = 'LOGIN';
  4300. }
  4301. switch ($authtype) {
  4302. case 'PLAIN':
  4303. // Start authentication
  4304. if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
  4305. return false;
  4306. }
  4307. // Send encoded username and password
  4308. if (!$this->sendCommand(
  4309. 'User & Password',
  4310. base64_encode("\0" . $username . "\0" . $password),
  4311. 235
  4312. )
  4313. ) {
  4314. return false;
  4315. }
  4316. break;
  4317. case 'LOGIN':
  4318. // Start authentication
  4319. if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
  4320. return false;
  4321. }
  4322. if (!$this->sendCommand("Username", base64_encode($username), 334)) {
  4323. return false;
  4324. }
  4325. if (!$this->sendCommand("Password", base64_encode($password), 235)) {
  4326. return false;
  4327. }
  4328. break;
  4329. case 'XOAUTH2':
  4330. //If the OAuth Instance is not set. Can be a case when PHPMailer is used
  4331. //instead of PHPMailerOAuth
  4332. if (is_null($OAuth)) {
  4333. return false;
  4334. }
  4335. $oauth = $OAuth->getOauth64();
  4336.  
  4337. // Start authentication
  4338. if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
  4339. return false;
  4340. }
  4341. break;
  4342. case 'NTLM':
  4343. /*
  4344. * ntlm_sasl_client.php
  4345. * Bundled with Permission
  4346. *
  4347. * How to telnet in windows:
  4348. * http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx
  4349. * PROTOCOL Docs http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication
  4350. */
  4351. require_once 'extras/ntlm_sasl_client.php';
  4352. $temp = new stdClass;
  4353. $ntlm_client = new ntlm_sasl_client_class;
  4354. //Check that functions are available
  4355. if (!$ntlm_client->Initialize($temp)) {
  4356. $this->setError($temp->error);
  4357. $this->edebug(
  4358. 'You need to enable some modules in your php.ini file: '
  4359. . $this->error['error'],
  4360. self::DEBUG_CLIENT
  4361. );
  4362. return false;
  4363. }
  4364. //msg1
  4365. $msg1 = $ntlm_client->TypeMsg1($realm, $workstation); //msg1
  4366.  
  4367. if (!$this->sendCommand(
  4368. 'AUTH NTLM',
  4369. 'AUTH NTLM ' . base64_encode($msg1),
  4370. 334
  4371. )
  4372. ) {
  4373. return false;
  4374. }
  4375. //Though 0 based, there is a white space after the 3 digit number
  4376. //msg2
  4377. $challenge = substr($this->last_reply, 3);
  4378. $challenge = base64_decode($challenge);
  4379. $ntlm_res = $ntlm_client->NTLMResponse(
  4380. substr($challenge, 24, 8),
  4381. $password
  4382. );
  4383. //msg3
  4384. $msg3 = $ntlm_client->TypeMsg3(
  4385. $ntlm_res,
  4386. $username,
  4387. $realm,
  4388. $workstation
  4389. );
  4390. // send encoded username
  4391. return $this->sendCommand('Username', base64_encode($msg3), 235);
  4392. case 'CRAM-MD5':
  4393. // Start authentication
  4394. if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
  4395. return false;
  4396. }
  4397. // Get the challenge
  4398. $challenge = base64_decode(substr($this->last_reply, 4));
  4399.  
  4400. // Build the response
  4401. $response = $username . ' ' . $this->hmac($challenge, $password);
  4402.  
  4403. // send encoded credentials
  4404. return $this->sendCommand('Username', base64_encode($response), 235);
  4405. default:
  4406. $this->setError("Authentication method \"$authtype\" is not supported");
  4407. return false;
  4408. }
  4409. return true;
  4410. }
  4411.  
  4412. /**
  4413. * Calculate an MD5 HMAC hash.
  4414. * Works like hash_hmac('md5', $data, $key)
  4415. * in case that function is not available
  4416. * @param string $data The data to hash
  4417. * @param string $key The key to hash with
  4418. * @access protected
  4419. * @return string
  4420. */
  4421. protected function hmac($data, $key)
  4422. {
  4423. if (function_exists('hash_hmac')) {
  4424. return hash_hmac('md5', $data, $key);
  4425. }
  4426.  
  4427. // The following borrowed from
  4428. // http://php.net/manual/en/function.mhash.php#27225
  4429.  
  4430. // RFC 2104 HMAC implementation for php.
  4431. // Creates an md5 HMAC.
  4432. // Eliminates the need to install mhash to compute a HMAC
  4433. // by Lance Rushing
  4434.  
  4435. $bytelen = 64; // byte length for md5
  4436. if (strlen($key) > $bytelen) {
  4437. $key = pack('H*', md5($key));
  4438. }
  4439. $key = str_pad($key, $bytelen, chr(0x00));
  4440. $ipad = str_pad('', $bytelen, chr(0x36));
  4441. $opad = str_pad('', $bytelen, chr(0x5c));
  4442. $k_ipad = $key ^ $ipad;
  4443. $k_opad = $key ^ $opad;
  4444.  
  4445. return md5($k_opad . pack('H*', md5($k_ipad . $data)));
  4446. }
  4447.  
  4448. /**
  4449. * Check connection state.
  4450. * @access public
  4451. * @return boolean True if connected.
  4452. */
  4453. public function connected()
  4454. {
  4455. if (is_resource($this->smtp_conn)) {
  4456. $sock_status = stream_get_meta_data($this->smtp_conn);
  4457. if ($sock_status['eof']) {
  4458. // The socket is valid but we are not connected
  4459. $this->edebug(
  4460. 'SMTP NOTICE: EOF caught while checking if connected',
  4461. self::DEBUG_CLIENT
  4462. );
  4463. $this->close();
  4464. return false;
  4465. }
  4466. return true; // everything looks good
  4467. }
  4468. return false;
  4469. }
  4470.  
  4471. /**
  4472. * Close the socket and clean up the state of the class.
  4473. * Don't use this function without first trying to use QUIT.
  4474. * @see quit()
  4475. * @access public
  4476. * @return void
  4477. */
  4478. public function close()
  4479. {
  4480. $this->setError('');
  4481. $this->server_caps = null;
  4482. $this->helo_rply = null;
  4483. if (is_resource($this->smtp_conn)) {
  4484. // close the connection and cleanup
  4485. fclose($this->smtp_conn);
  4486. $this->smtp_conn = null; //Makes for cleaner serialization
  4487. $this->edebug('Connection: closed', self::DEBUG_CONNECTION);
  4488. }
  4489. }
  4490.  
  4491. /**
  4492. * Send an SMTP DATA command.
  4493. * Issues a data command and sends the msg_data to the server,
  4494. * finializing the mail transaction. $msg_data is the message
  4495. * that is to be send with the headers. Each header needs to be
  4496. * on a single line followed by a <CRLF> with the message headers
  4497. * and the message body being separated by and additional <CRLF>.
  4498. * Implements rfc 821: DATA <CRLF>
  4499. * @param string $msg_data Message data to send
  4500. * @access public
  4501. * @return boolean
  4502. */
  4503. public function data($msg_data)
  4504. {
  4505. //This will use the standard timelimit
  4506. if (!$this->sendCommand('DATA', 'DATA', 354)) {
  4507. return false;
  4508. }
  4509.  
  4510. /* The server is ready to accept data!
  4511. * According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF)
  4512. * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
  4513. * smaller lines to fit within the limit.
  4514. * We will also look for lines that start with a '.' and prepend an additional '.'.
  4515. * NOTE: this does not count towards line-length limit.
  4516. */
  4517.  
  4518. // Normalize line breaks before exploding
  4519. $lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data));
  4520.  
  4521. /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
  4522. * of the first line (':' separated) does not contain a space then it _should_ be a header and we will
  4523. * process all lines before a blank line as headers.
  4524. */
  4525.  
  4526. $field = substr($lines[0], 0, strpos($lines[0], ':'));
  4527. $in_headers = false;
  4528. if (!empty($field) && strpos($field, ' ') === false) {
  4529. $in_headers = true;
  4530. }
  4531.  
  4532. foreach ($lines as $line) {
  4533. $lines_out = array();
  4534. if ($in_headers and $line == '') {
  4535. $in_headers = false;
  4536. }
  4537. //Break this line up into several smaller lines if it's too long
  4538. //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len),
  4539. while (isset($line[self::MAX_LINE_LENGTH])) {
  4540. //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on
  4541. //so as to avoid breaking in the middle of a word
  4542. $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
  4543. //Deliberately matches both false and 0
  4544. if (!$pos) {
  4545. //No nice break found, add a hard break
  4546. $pos = self::MAX_LINE_LENGTH - 1;
  4547. $lines_out[] = substr($line, 0, $pos);
  4548. $line = substr($line, $pos);
  4549. } else {
  4550. //Break at the found point
  4551. $lines_out[] = substr($line, 0, $pos);
  4552. //Move along by the amount we dealt with
  4553. $line = substr($line, $pos + 1);
  4554. }
  4555. //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1
  4556. if ($in_headers) {
  4557. $line = "\t" . $line;
  4558. }
  4559. }
  4560. $lines_out[] = $line;
  4561.  
  4562. //Send the lines to the server
  4563. foreach ($lines_out as $line_out) {
  4564. //RFC2821 section 4.5.2
  4565. if (!empty($line_out) and $line_out[0] == '.') {
  4566. $line_out = '.' . $line_out;
  4567. }
  4568. $this->client_send($line_out . self::CRLF);
  4569. }
  4570. }
  4571.  
  4572. //Message data has been sent, complete the command
  4573. //Increase timelimit for end of DATA command
  4574. $savetimelimit = $this->Timelimit;
  4575. $this->Timelimit = $this->Timelimit * 2;
  4576. $result = $this->sendCommand('DATA END', '.', 250);
  4577. //Restore timelimit
  4578. $this->Timelimit = $savetimelimit;
  4579. return $result;
  4580. }
  4581.  
  4582. /**
  4583. * Send an SMTP HELO or EHLO command.
  4584. * Used to identify the sending server to the receiving server.
  4585. * This makes sure that client and server are in a known state.
  4586. * Implements RFC 821: HELO <SP> <domain> <CRLF>
  4587. * and RFC 2821 EHLO.
  4588. * @param string $host The host name or IP to connect to
  4589. * @access public
  4590. * @return boolean
  4591. */
  4592. public function hello($host = '')
  4593. {
  4594. //Try extended hello first (RFC 2821)
  4595. return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host));
  4596. }
  4597.  
  4598. /**
  4599. * Send an SMTP HELO or EHLO command.
  4600. * Low-level implementation used by hello()
  4601. * @see hello()
  4602. * @param string $hello The HELO string
  4603. * @param string $host The hostname to say we are
  4604. * @access protected
  4605. * @return boolean
  4606. */
  4607. protected function sendHello($hello, $host)
  4608. {
  4609. $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
  4610. $this->helo_rply = $this->last_reply;
  4611. if ($noerror) {
  4612. $this->parseHelloFields($hello);
  4613. } else {
  4614. $this->server_caps = null;
  4615. }
  4616. return $noerror;
  4617. }
  4618.  
  4619. /**
  4620. * Parse a reply to HELO/EHLO command to discover server extensions.
  4621. * In case of HELO, the only parameter that can be discovered is a server name.
  4622. * @access protected
  4623. * @param string $type - 'HELO' or 'EHLO'
  4624. */
  4625. protected function parseHelloFields($type)
  4626. {
  4627. $this->server_caps = array();
  4628. $lines = explode("\n", $this->last_reply);
  4629.  
  4630. foreach ($lines as $n => $s) {
  4631. //First 4 chars contain response code followed by - or space
  4632. $s = trim(substr($s, 4));
  4633. if (empty($s)) {
  4634. continue;
  4635. }
  4636. $fields = explode(' ', $s);
  4637. if (!empty($fields)) {
  4638. if (!$n) {
  4639. $name = $type;
  4640. $fields = $fields[0];
  4641. } else {
  4642. $name = array_shift($fields);
  4643. switch ($name) {
  4644. case 'SIZE':
  4645. $fields = ($fields ? $fields[0] : 0);
  4646. break;
  4647. case 'AUTH':
  4648. if (!is_array($fields)) {
  4649. $fields = array();
  4650. }
  4651. break;
  4652. default:
  4653. $fields = true;
  4654. }
  4655. }
  4656. $this->server_caps[$name] = $fields;
  4657. }
  4658. }
  4659. }
  4660.  
  4661. /**
  4662. * Send an SMTP MAIL command.
  4663. * Starts a mail transaction from the email address specified in
  4664. * $from. Returns true if successful or false otherwise. If True
  4665. * the mail transaction is started and then one or more recipient
  4666. * commands may be called followed by a data command.
  4667. * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
  4668. * @param string $from Source address of this message
  4669. * @access public
  4670. * @return boolean
  4671. */
  4672. public function mail($from)
  4673. {
  4674. $useVerp = ($this->do_verp ? ' XVERP' : '');
  4675. return $this->sendCommand(
  4676. 'MAIL FROM',
  4677. 'MAIL FROM:<' . $from . '>' . $useVerp,
  4678. 250
  4679. );
  4680. }
  4681.  
  4682. /**
  4683. * Send an SMTP QUIT command.
  4684. * Closes the socket if there is no error or the $close_on_error argument is true.
  4685. * Implements from rfc 821: QUIT <CRLF>
  4686. * @param boolean $close_on_error Should the connection close if an error occurs?
  4687. * @access public
  4688. * @return boolean
  4689. */
  4690. public function quit($close_on_error = true)
  4691. {
  4692. $noerror = $this->sendCommand('QUIT', 'QUIT', 221);
  4693. $err = $this->error; //Save any error
  4694. if ($noerror or $close_on_error) {
  4695. $this->close();
  4696. $this->error = $err; //Restore any error from the quit command
  4697. }
  4698. return $noerror;
  4699. }
  4700.  
  4701. /**
  4702. * Send an SMTP RCPT command.
  4703. * Sets the TO argument to $toaddr.
  4704. * Returns true if the recipient was accepted false if it was rejected.
  4705. * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
  4706. * @param string $address The address the message is being sent to
  4707. * @access public
  4708. * @return boolean
  4709. */
  4710. public function recipient($address)
  4711. {
  4712. return $this->sendCommand(
  4713. 'RCPT TO',
  4714. 'RCPT TO:<' . $address . '>',
  4715. array(250, 251)
  4716. );
  4717. }
  4718.  
  4719. /**
  4720. * Send an SMTP RSET command.
  4721. * Abort any transaction that is currently in progress.
  4722. * Implements rfc 821: RSET <CRLF>
  4723. * @access public
  4724. * @return boolean True on success.
  4725. */
  4726. public function reset()
  4727. {
  4728. return $this->sendCommand('RSET', 'RSET', 250);
  4729. }
  4730.  
  4731. /**
  4732. * Send a command to an SMTP server and check its return code.
  4733. * @param string $command The command name - not sent to the server
  4734. * @param string $commandstring The actual command to send
  4735. * @param integer|array $expect One or more expected integer success codes
  4736. * @access protected
  4737. * @return boolean True on success.
  4738. */
  4739. protected function sendCommand($command, $commandstring, $expect)
  4740. {
  4741. if (!$this->connected()) {
  4742. $this->setError("Called $command without being connected");
  4743. return false;
  4744. }
  4745. //Reject line breaks in all commands
  4746. if (strpos($commandstring, "\n") !== false or strpos($commandstring, "\r") !== false) {
  4747. $this->setError("Command '$command' contained line breaks");
  4748. return false;
  4749. }
  4750. $this->client_send($commandstring . self::CRLF);
  4751.  
  4752. $this->last_reply = $this->get_lines();
  4753. // Fetch SMTP code and possible error code explanation
  4754. $matches = array();
  4755. if (preg_match("/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/", $this->last_reply, $matches)) {
  4756. $code = $matches[1];
  4757. $code_ex = (count($matches) > 2 ? $matches[2] : null);
  4758. // Cut off error code from each response line
  4759. $detail = preg_replace(
  4760. "/{$code}[ -]".($code_ex ? str_replace('.', '\\.', $code_ex).' ' : '')."/m",
  4761. '',
  4762. $this->last_reply
  4763. );
  4764. } else {
  4765. // Fall back to simple parsing if regex fails
  4766. $code = substr($this->last_reply, 0, 3);
  4767. $code_ex = null;
  4768. $detail = substr($this->last_reply, 4);
  4769. }
  4770.  
  4771. $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
  4772.  
  4773. if (!in_array($code, (array)$expect)) {
  4774. $this->setError(
  4775. "$command command failed",
  4776. $detail,
  4777. $code,
  4778. $code_ex
  4779. );
  4780. $this->edebug(
  4781. 'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply,
  4782. self::DEBUG_CLIENT
  4783. );
  4784. return false;
  4785. }
  4786.  
  4787. $this->setError('');
  4788. return true;
  4789. }
  4790.  
  4791. /**
  4792. * Send an SMTP SAML command.
  4793. * Starts a mail transaction from the email address specified in $from.
  4794. * Returns true if successful or false otherwise. If True
  4795. * the mail transaction is started and then one or more recipient
  4796. * commands may be called followed by a data command. This command
  4797. * will send the message to the users terminal if they are logged
  4798. * in and send them an email.
  4799. * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
  4800. * @param string $from The address the message is from
  4801. * @access public
  4802. * @return boolean
  4803. */
  4804. public function sendAndMail($from)
  4805. {
  4806. return $this->sendCommand('SAML', "SAML FROM:$from", 250);
  4807. }
  4808.  
  4809. /**
  4810. * Send an SMTP VRFY command.
  4811. * @param string $name The name to verify
  4812. * @access public
  4813. * @return boolean
  4814. */
  4815. public function verify($name)
  4816. {
  4817. return $this->sendCommand('VRFY', "VRFY $name", array(250, 251));
  4818. }
  4819.  
  4820. /**
  4821. * Send an SMTP NOOP command.
  4822. * Used to keep keep-alives alive, doesn't actually do anything
  4823. * @access public
  4824. * @return boolean
  4825. */
  4826. public function noop()
  4827. {
  4828. return $this->sendCommand('NOOP', 'NOOP', 250);
  4829. }
  4830.  
  4831. /**
  4832. * Send an SMTP TURN command.
  4833. * This is an optional command for SMTP that this class does not support.
  4834. * This method is here to make the RFC821 Definition complete for this class
  4835. * and _may_ be implemented in future
  4836. * Implements from rfc 821: TURN <CRLF>
  4837. * @access public
  4838. * @return boolean
  4839. */
  4840. public function turn()
  4841. {
  4842. $this->setError('The SMTP TURN command is not implemented');
  4843. $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
  4844. return false;
  4845. }
  4846.  
  4847. /**
  4848. * Send raw data to the server.
  4849. * @param string $data The data to send
  4850. * @access public
  4851. * @return integer|boolean The number of bytes sent to the server or false on error
  4852. */
  4853. public function client_send($data)
  4854. {
  4855. $this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT);
  4856. return fwrite($this->smtp_conn, $data);
  4857. }
  4858.  
  4859. /**
  4860. * Get the latest error.
  4861. * @access public
  4862. * @return array
  4863. */
  4864. public function getError()
  4865. {
  4866. return $this->error;
  4867. }
  4868.  
  4869. /**
  4870. * Get SMTP extensions available on the server
  4871. * @access public
  4872. * @return array|null
  4873. */
  4874. public function getServerExtList()
  4875. {
  4876. return $this->server_caps;
  4877. }
  4878.  
  4879. /**
  4880. * A multipurpose method
  4881. * The method works in three ways, dependent on argument value and current state
  4882. * 1. HELO/EHLO was not sent - returns null and set up $this->error
  4883. * 2. HELO was sent
  4884. * $name = 'HELO': returns server name
  4885. * $name = 'EHLO': returns boolean false
  4886. * $name = any string: returns null and set up $this->error
  4887. * 3. EHLO was sent
  4888. * $name = 'HELO'|'EHLO': returns server name
  4889. * $name = any string: if extension $name exists, returns boolean True
  4890. * or its options. Otherwise returns boolean False
  4891. * In other words, one can use this method to detect 3 conditions:
  4892. * - null returned: handshake was not or we don't know about ext (refer to $this->error)
  4893. * - false returned: the requested feature exactly not exists
  4894. * - positive value returned: the requested feature exists
  4895. * @param string $name Name of SMTP extension or 'HELO'|'EHLO'
  4896. * @return mixed
  4897. */
  4898. public function getServerExt($name)
  4899. {
  4900. if (!$this->server_caps) {
  4901. $this->setError('No HELO/EHLO was sent');
  4902. return null;
  4903. }
  4904.  
  4905. // the tight logic knot ;)
  4906. if (!array_key_exists($name, $this->server_caps)) {
  4907. if ($name == 'HELO') {
  4908. return $this->server_caps['EHLO'];
  4909. }
  4910. if ($name == 'EHLO' || array_key_exists('EHLO', $this->server_caps)) {
  4911. return false;
  4912. }
  4913. $this->setError('HELO handshake was used. Client knows nothing about server extensions');
  4914. return null;
  4915. }
  4916.  
  4917. return $this->server_caps[$name];
  4918. }
  4919.  
  4920. /**
  4921. * Get the last reply from the server.
  4922. * @access public
  4923. * @return string
  4924. */
  4925. public function getLastReply()
  4926. {
  4927. return $this->last_reply;
  4928. }
  4929.  
  4930. /**
  4931. * Read the SMTP server's response.
  4932. * Either before eof or socket timeout occurs on the operation.
  4933. * With SMTP we can tell if we have more lines to read if the
  4934. * 4th character is '-' symbol. If it is a space then we don't
  4935. * need to read anything else.
  4936. * @access protected
  4937. * @return string
  4938. */
  4939. protected function get_lines()
  4940. {
  4941. // If the connection is bad, give up straight away
  4942. if (!is_resource($this->smtp_conn)) {
  4943. return '';
  4944. }
  4945. $data = '';
  4946. $endtime = 0;
  4947. stream_set_timeout($this->smtp_conn, $this->Timeout);
  4948. if ($this->Timelimit > 0) {
  4949. $endtime = time() + $this->Timelimit;
  4950. }
  4951. while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
  4952. $str = @fgets($this->smtp_conn, 515);
  4953. $this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL);
  4954. $this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL);
  4955. $data .= $str;
  4956. // If 4th character is a space, we are done reading, break the loop, micro-optimisation over strlen
  4957. if ((isset($str[3]) and $str[3] == ' ')) {
  4958. break;
  4959. }
  4960. // Timed-out? Log and break
  4961. $info = stream_get_meta_data($this->smtp_conn);
  4962. if ($info['timed_out']) {
  4963. $this->edebug(
  4964. 'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)',
  4965. self::DEBUG_LOWLEVEL
  4966. );
  4967. break;
  4968. }
  4969. // Now check if reads took too long
  4970. if ($endtime and time() > $endtime) {
  4971. $this->edebug(
  4972. 'SMTP -> get_lines(): timelimit reached ('.
  4973. $this->Timelimit . ' sec)',
  4974. self::DEBUG_LOWLEVEL
  4975. );
  4976. break;
  4977. }
  4978. }
  4979. return $data;
  4980. }
  4981.  
  4982. /**
  4983. * Enable or disable VERP address generation.
  4984. * @param boolean $enabled
  4985. */
  4986. public function setVerp($enabled = false)
  4987. {
  4988. $this->do_verp = $enabled;
  4989. }
  4990.  
  4991. /**
  4992. * Get VERP address generation mode.
  4993. * @return boolean
  4994. */
  4995. public function getVerp()
  4996. {
  4997. return $this->do_verp;
  4998. }
  4999.  
  5000. /**
  5001. * Set error messages and codes.
  5002. * @param string $message The error message
  5003. * @param string $detail Further detail on the error
  5004. * @param string $smtp_code An associated SMTP error code
  5005. * @param string $smtp_code_ex Extended SMTP code
  5006. */
  5007. protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '')
  5008. {
  5009. $this->error = array(
  5010. 'error' => $message,
  5011. 'detail' => $detail,
  5012. 'smtp_code' => $smtp_code,
  5013. 'smtp_code_ex' => $smtp_code_ex
  5014. );
  5015. }
  5016.  
  5017. /**
  5018. * Set debug output method.
  5019. * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it.
  5020. */
  5021. public function setDebugOutput($method = 'echo')
  5022. {
  5023. $this->Debugoutput = $method;
  5024. }
  5025.  
  5026. /**
  5027. * Get debug output method.
  5028. * @return string
  5029. */
  5030. public function getDebugOutput()
  5031. {
  5032. return $this->Debugoutput;
  5033. }
  5034.  
  5035. /**
  5036. * Set debug output level.
  5037. * @param integer $level
  5038. */
  5039. public function setDebugLevel($level = 0)
  5040. {
  5041. $this->do_debug = $level;
  5042. }
  5043.  
  5044. /**
  5045. * Get debug output level.
  5046. * @return integer
  5047. */
  5048. public function getDebugLevel()
  5049. {
  5050. return $this->do_debug;
  5051. }
  5052.  
  5053. /**
  5054. * Set SMTP timeout.
  5055. * @param integer $timeout
  5056. */
  5057. public function setTimeout($timeout = 0)
  5058. {
  5059. $this->Timeout = $timeout;
  5060. }
  5061.  
  5062. /**
  5063. * Get SMTP timeout.
  5064. * @return integer
  5065. */
  5066. public function getTimeout()
  5067. {
  5068. return $this->Timeout;
  5069. }
  5070. }
Add Comment
Please, Sign In to add comment