Guest User

Untitled

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