Guest User

Untitled

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