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

/webroot/lib/PHPMailer/class.phpmailer.php

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