PageRenderTime 142ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 1ms

/mailer/class.phpmailer.php

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