PageRenderTime 73ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-content/plugins/amazon-ses-and-dkim-mailer/php-mailer/class.phpmailer.php

https://bitbucket.org/broderboy/shannonbroder-wordpress
PHP | 3041 lines | 1808 code | 233 blank | 1000 comment | 294 complexity | 4b1bca0f8a005a0f460f10ea44242f04 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, AGPL-1.0
  1. <?php
  2. /*~ class.phpmailer.php
  3. .---------------------------------------------------------------------------.
  4. | Software: PHPMailer - PHP email class |
  5. | Version: 5.2.6 |
  6. | Site: https://github.com/PHPMailer/PHPMailer/ |
  7. | ------------------------------------------------------------------------- |
  8. | Admins: Marcus Bointon |
  9. | Admins: Jim Jagielski |
  10. | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
  11. | : Marcus Bointon (coolbru) phpmailer@synchromedia.co.uk |
  12. | : Jim Jagielski (jimjag) jimjag@gmail.com |
  13. | Founder: Brent R. Matzelle (original founder) |
  14. | Copyright (c) 2010-2012, Jim Jagielski. All Rights Reserved. |
  15. | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. |
  16. | Copyright (c) 2001-2003, Brent R. Matzelle |
  17. | ------------------------------------------------------------------------- |
  18. | License: Distributed under the Lesser General Public License (LGPL) |
  19. | http://www.gnu.org/copyleft/lesser.html |
  20. | This program is distributed in the hope that it will be useful - WITHOUT |
  21. | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
  22. | FITNESS FOR A PARTICULAR PURPOSE. |
  23. '---------------------------------------------------------------------------'
  24. */
  25. /**
  26. * PHPMailer - PHP email creation and transport class
  27. * NOTE: Requires PHP version 5 or later
  28. * @package PHPMailer
  29. * @author Andy Prevost
  30. * @author Marcus Bointon
  31. * @author Jim Jagielski
  32. * @copyright 2010 - 2012 Jim Jagielski
  33. * @copyright 2004 - 2009 Andy Prevost
  34. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  35. */
  36. if (version_compare(PHP_VERSION, '5.0.0', '<') ) {
  37. exit("Sorry, PHPMailer will only run on PHP version 5 or greater!\n");
  38. }
  39. /**
  40. * PHP email creation and transport class
  41. * @package PHPMailer
  42. */
  43. class PHPMailer {
  44. /////////////////////////////////////////////////
  45. // PROPERTIES, PUBLIC
  46. /////////////////////////////////////////////////
  47. /**
  48. * Email priority (1 = High, 3 = Normal, 5 = low).
  49. * @var int
  50. */
  51. public $Priority = 3;
  52. /**
  53. * Sets the CharSet of the message.
  54. * @var string
  55. */
  56. public $CharSet = 'iso-8859-1';
  57. /**
  58. * Sets the Content-type of the message.
  59. * @var string
  60. */
  61. public $ContentType = 'text/plain';
  62. /**
  63. * Sets the Encoding of the message. Options for this are
  64. * "8bit", "7bit", "binary", "base64", and "quoted-printable".
  65. * @var string
  66. */
  67. public $Encoding = '8bit';
  68. /**
  69. * Holds the most recent mailer error message.
  70. * @var string
  71. */
  72. public $ErrorInfo = '';
  73. /**
  74. * Sets the From email address for the message.
  75. * @var string
  76. */
  77. public $From = 'root@localhost';
  78. /**
  79. * Sets the From name of the message.
  80. * @var string
  81. */
  82. public $FromName = 'Root User';
  83. /**
  84. * Sets the Sender email (Return-Path) of the message.
  85. * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  86. * @var string
  87. */
  88. public $Sender = '';
  89. /**
  90. * Sets the Return-Path of the message. If empty, it will
  91. * be set to either From or Sender.
  92. * @var string
  93. */
  94. public $ReturnPath = '';
  95. /**
  96. * Sets the Subject of the message.
  97. * @var string
  98. */
  99. public $Subject = '';
  100. /**
  101. * An HTML or plain text message body.
  102. * If HTML then call IsHTML(true).
  103. * @var string
  104. */
  105. public $Body = '';
  106. /**
  107. * The plain-text message body.
  108. * This body can be read by mail clients that do not have HTML email
  109. * capability such as mutt & Eudora.
  110. * Clients that can read HTML will view the normal Body.
  111. * @var string
  112. */
  113. public $AltBody = '';
  114. /**
  115. * An iCal message part body
  116. * Only supported in simple alt or alt_inline message types
  117. * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator
  118. * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
  119. * @link http://kigkonsult.se/iCalcreator/
  120. * @var string
  121. */
  122. public $Ical = '';
  123. /**
  124. * Stores the complete compiled MIME message body.
  125. * @var string
  126. * @access protected
  127. */
  128. protected $MIMEBody = '';
  129. /**
  130. * Stores the complete compiled MIME message headers.
  131. * @var string
  132. * @access protected
  133. */
  134. protected $MIMEHeader = '';
  135. /**
  136. * Stores the extra header list which CreateHeader() doesn't fold in
  137. * @var string
  138. * @access protected
  139. */
  140. protected $mailHeader = '';
  141. /**
  142. * Sets word wrapping on the body of the message to a given number of
  143. * characters.
  144. * @var int
  145. */
  146. public $WordWrap = 0;
  147. /**
  148. * Method to send mail: ("mail", "sendmail", or "smtp").
  149. * @var string
  150. */
  151. public $Mailer = 'mail';
  152. /**
  153. * Sets the path of the sendmail program.
  154. * @var string
  155. */
  156. public $Sendmail = '/usr/sbin/sendmail';
  157. /**
  158. * Determine if mail() uses a fully sendmail compatible MTA that
  159. * supports sendmail's "-oi -f" options
  160. * @var boolean
  161. */
  162. public $UseSendmailOptions = true;
  163. /**
  164. * Path to PHPMailer plugins. Useful if the SMTP class
  165. * is in a different directory than the PHP include path.
  166. * @var string
  167. */
  168. public $PluginDir = '';
  169. /**
  170. * Sets the email address that a reading confirmation will be sent.
  171. * @var string
  172. */
  173. public $ConfirmReadingTo = '';
  174. /**
  175. * Sets the hostname to use in Message-Id and Received headers
  176. * and as default HELO string. If empty, the value returned
  177. * by SERVER_NAME is used or 'localhost.localdomain'.
  178. * @var string
  179. */
  180. public $Hostname = '';
  181. /**
  182. * Sets the message ID to be used in the Message-Id header.
  183. * If empty, a unique id will be generated.
  184. * @var string
  185. */
  186. public $MessageID = '';
  187. /**
  188. * Sets the message Date to be used in the Date header.
  189. * If empty, the current date will be added.
  190. * @var string
  191. */
  192. public $MessageDate = '';
  193. /////////////////////////////////////////////////
  194. // PROPERTIES FOR SMTP
  195. /////////////////////////////////////////////////
  196. /**
  197. * Sets the SMTP hosts.
  198. *
  199. * All hosts must be separated by a
  200. * semicolon. You can also specify a different port
  201. * for each host by using this format: [hostname:port]
  202. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  203. * Hosts will be tried in order.
  204. * @var string
  205. */
  206. public $Host = 'localhost';
  207. /**
  208. * Sets the default SMTP server port.
  209. * @var int
  210. */
  211. public $Port = 25;
  212. /**
  213. * Sets the SMTP HELO of the message (Default is $Hostname).
  214. * @var string
  215. */
  216. public $Helo = '';
  217. /**
  218. * Sets connection prefix. Options are "", "ssl" or "tls"
  219. * @var string
  220. */
  221. public $SMTPSecure = '';
  222. /**
  223. * Sets SMTP authentication. Utilizes the Username and Password variables.
  224. * @var bool
  225. */
  226. public $SMTPAuth = false;
  227. /**
  228. * Sets SMTP username.
  229. * @var string
  230. */
  231. public $Username = '';
  232. /**
  233. * Sets SMTP password.
  234. * @var string
  235. */
  236. public $Password = '';
  237. /**
  238. * Sets SMTP auth type. Options are LOGIN | PLAIN | NTLM | CRAM-MD5 (default LOGIN)
  239. * @var string
  240. */
  241. public $AuthType = '';
  242. /**
  243. * Sets SMTP realm.
  244. * @var string
  245. */
  246. public $Realm = '';
  247. /**
  248. * Sets SMTP workstation.
  249. * @var string
  250. */
  251. public $Workstation = '';
  252. /**
  253. * Sets the SMTP server timeout in seconds.
  254. * This function will not work with the win32 version.
  255. * @var int
  256. */
  257. public $Timeout = 10;
  258. /**
  259. * Sets SMTP class debugging on or off.
  260. * @var bool
  261. */
  262. public $SMTPDebug = false;
  263. /**
  264. * Sets the function/method to use for debugging output.
  265. * Right now we only honor "echo" or "error_log"
  266. * @var string
  267. */
  268. public $Debugoutput = "echo";
  269. /**
  270. * Prevents the SMTP connection from being closed after each mail
  271. * sending. If this is set to true then to close the connection
  272. * requires an explicit call to SmtpClose().
  273. * @var bool
  274. */
  275. public $SMTPKeepAlive = false;
  276. /**
  277. * Provides the ability to have the TO field process individual
  278. * emails, instead of sending to entire TO addresses
  279. * @var bool
  280. */
  281. public $SingleTo = false;
  282. /**
  283. * Should we generate VERP addresses when sending via SMTP?
  284. * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
  285. * @var bool
  286. */
  287. public $do_verp = false;
  288. /**
  289. * If SingleTo is true, this provides the array to hold the email addresses
  290. * @var bool
  291. */
  292. public $SingleToArray = array();
  293. /**
  294. * Should we allow sending messages with empty body?
  295. * @var bool
  296. */
  297. public $AllowEmpty = false;
  298. /**
  299. * Provides the ability to change the generic line ending
  300. * NOTE: The default remains '\n'. We force CRLF where we KNOW
  301. * it must be used via self::CRLF
  302. * @var string
  303. */
  304. public $LE = "\n";
  305. /**
  306. * Used with DKIM Signing
  307. * required parameter if DKIM is enabled
  308. *
  309. * domain selector example domainkey
  310. * @var string
  311. */
  312. public $DKIM_selector = '';
  313. /**
  314. * Used with DKIM Signing
  315. * required if DKIM is enabled, in format of email address 'you@yourdomain.com' typically used as the source of the email
  316. * @var string
  317. */
  318. public $DKIM_identity = '';
  319. /**
  320. * Used with DKIM Signing
  321. * optional parameter if your private key requires a passphras
  322. * @var string
  323. */
  324. public $DKIM_passphrase = '';
  325. /**
  326. * Used with DKIM Singing
  327. * required if DKIM is enabled, in format of email address 'domain.com'
  328. * @var string
  329. */
  330. public $DKIM_domain = '';
  331. /**
  332. * Used with DKIM Signing
  333. * required if DKIM is enabled, path to private key file
  334. * @var string
  335. */
  336. public $DKIM_private = '';
  337. /**
  338. * Callback Action function name.
  339. * The function that handles the result of the send email action.
  340. * It is called out by Send() for each email sent.
  341. *
  342. * Value can be:
  343. * - 'function_name' for function names
  344. * - 'Class::Method' for static method calls
  345. * - array($object, 'Method') for calling methods on $object
  346. * See http://php.net/is_callable manual page for more details.
  347. *
  348. * Parameters:
  349. * bool $result result of the send action
  350. * string $to email address of the recipient
  351. * string $cc cc email addresses
  352. * string $bcc bcc email addresses
  353. * string $subject the subject
  354. * string $body the email body
  355. * string $from email address of sender
  356. * @var string
  357. */
  358. public $action_function = ''; //'callbackAction';
  359. /**
  360. * Sets the PHPMailer Version number
  361. * @var string
  362. */
  363. public $Version = '5.2.6';
  364. /**
  365. * What to use in the X-Mailer header
  366. * @var string NULL for default, whitespace for None, or actual string to use
  367. */
  368. public $XMailer = '';
  369. /////////////////////////////////////////////////
  370. // PROPERTIES, PRIVATE AND PROTECTED
  371. /////////////////////////////////////////////////
  372. /**
  373. * @var SMTP An instance of the SMTP sender class
  374. * @access protected
  375. */
  376. protected $smtp = null;
  377. /**
  378. * @var array An array of 'to' addresses
  379. * @access protected
  380. */
  381. protected $to = array();
  382. /**
  383. * @var array An array of 'cc' addresses
  384. * @access protected
  385. */
  386. protected $cc = array();
  387. /**
  388. * @var array An array of 'bcc' addresses
  389. * @access protected
  390. */
  391. protected $bcc = array();
  392. /**
  393. * @var array An array of reply-to name and address
  394. * @access protected
  395. */
  396. protected $ReplyTo = array();
  397. /**
  398. * @var array An array of all kinds of addresses: to, cc, bcc, replyto
  399. * @access protected
  400. */
  401. protected $all_recipients = array();
  402. /**
  403. * @var array An array of attachments
  404. * @access protected
  405. */
  406. protected $attachment = array();
  407. /**
  408. * @var array An array of custom headers
  409. * @access protected
  410. */
  411. protected $CustomHeader = array();
  412. /**
  413. * @var string The message's MIME type
  414. * @access protected
  415. */
  416. protected $message_type = '';
  417. /**
  418. * @var array An array of MIME boundary strings
  419. * @access protected
  420. */
  421. protected $boundary = array();
  422. /**
  423. * @var array An array of available languages
  424. * @access protected
  425. */
  426. protected $language = array();
  427. /**
  428. * @var integer The number of errors encountered
  429. * @access protected
  430. */
  431. protected $error_count = 0;
  432. /**
  433. * @var string The filename of a DKIM certificate file
  434. * @access protected
  435. */
  436. protected $sign_cert_file = '';
  437. /**
  438. * @var string The filename of a DKIM key file
  439. * @access protected
  440. */
  441. protected $sign_key_file = '';
  442. /**
  443. * @var string The password of a DKIM key
  444. * @access protected
  445. */
  446. protected $sign_key_pass = '';
  447. /**
  448. * @var boolean Whether to throw exceptions for errors
  449. * @access protected
  450. */
  451. protected $exceptions = false;
  452. /**Amazon SES**/
  453. private $amazonses_object = NULL;
  454. private $amazonses_use_destinations = TRUE;
  455. private $amazonses_use_source = TRUE;
  456. private $amazonses_use_names = TRUE;
  457. private $amazonses_debug = FALSE;
  458. /////////////////////////////////////////////////
  459. // CONSTANTS
  460. /////////////////////////////////////////////////
  461. const STOP_MESSAGE = 0; // message only, continue processing
  462. const STOP_CONTINUE = 1; // message?, likely ok to continue processing
  463. const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
  464. const CRLF = "\r\n"; // SMTP RFC specified EOL
  465. /////////////////////////////////////////////////
  466. // METHODS, VARIABLES
  467. /////////////////////////////////////////////////
  468. /**
  469. * Calls actual mail() function, but in a safe_mode aware fashion
  470. * Also, unless sendmail_path points to sendmail (or something that
  471. * claims to be sendmail), don't pass params (not a perfect fix,
  472. * but it will do)
  473. * @param string $to To
  474. * @param string $subject Subject
  475. * @param string $body Message Body
  476. * @param string $header Additional Header(s)
  477. * @param string $params Params
  478. * @access private
  479. * @return bool
  480. */
  481. private function mail_passthru($to, $subject, $body, $header, $params) {
  482. if ( ini_get('safe_mode') || !($this->UseSendmailOptions) ) {
  483. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header);
  484. } else {
  485. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params);
  486. }
  487. return $rt;
  488. }
  489. /**
  490. * Outputs debugging info via user-defined method
  491. * @param string $str
  492. */
  493. protected function edebug($str) {
  494. switch ($this->Debugoutput) {
  495. case 'error_log':
  496. error_log($str);
  497. break;
  498. case 'html':
  499. //Cleans up output a bit for a better looking display that's HTML-safe
  500. echo htmlentities(preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, $this->CharSet)."<br>\n";
  501. break;
  502. case 'echo':
  503. default:
  504. //Just echoes exactly what was received
  505. echo $str;
  506. }
  507. }
  508. /**
  509. * Constructor
  510. * @param boolean $exceptions Should we throw external exceptions?
  511. */
  512. public function __construct($exceptions = false) {
  513. $this->exceptions = ($exceptions == true);
  514. }
  515. /**
  516. * Destructor
  517. */
  518. public function __destruct() {
  519. if ($this->Mailer == 'smtp') { //Close any open SMTP connection nicely
  520. $this->SmtpClose();
  521. }
  522. }
  523. /**
  524. * Sets message type to HTML.
  525. * @param bool $ishtml
  526. * @return void
  527. */
  528. public function IsHTML($ishtml = true) {
  529. if ($ishtml) {
  530. $this->ContentType = 'text/html';
  531. } else {
  532. $this->ContentType = 'text/plain';
  533. }
  534. }
  535. /**
  536. * Sets Mailer to send message using SMTP.
  537. * @return void
  538. */
  539. public function IsSMTP() {
  540. $this->Mailer = 'smtp';
  541. }
  542. /**
  543. * Sets Mailer to send message using PHP mail() function.
  544. * @return void
  545. */
  546. public function IsMail() {
  547. $this->Mailer = 'mail';
  548. }
  549. /**
  550. * Sets Mailer to send message using the $Sendmail program.
  551. * @return void
  552. */
  553. public function IsSendmail() {
  554. if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
  555. $this->Sendmail = '/var/qmail/bin/sendmail';
  556. }
  557. $this->Mailer = 'sendmail';
  558. }
  559. /**
  560. * Sets Mailer to send message using the qmail MTA.
  561. * @return void
  562. */
  563. public function IsQmail() {
  564. if (stristr(ini_get('sendmail_path'), 'qmail')) {
  565. $this->Sendmail = '/var/qmail/bin/sendmail';
  566. }
  567. $this->Mailer = 'sendmail';
  568. }
  569. /**
  570. * Sets Mailer to send message using Amazon Simple Email Service(SES).
  571. * @return void
  572. */
  573. public function IsAmazonSES() {
  574. $this->Mailer = 'amazonses';
  575. }
  576. /////////////////////////////////////////////////
  577. // METHODS, RECIPIENTS
  578. /////////////////////////////////////////////////
  579. /**
  580. * Adds a "To" address.
  581. * @param string $address
  582. * @param string $name
  583. * @return boolean true on success, false if address already used
  584. */
  585. public function AddAddress($address, $name = '') {
  586. return $this->AddAnAddress('to', $address, $name);
  587. }
  588. /**
  589. * Adds a "Cc" address.
  590. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  591. * @param string $address
  592. * @param string $name
  593. * @return boolean true on success, false if address already used
  594. */
  595. public function AddCC($address, $name = '') {
  596. return $this->AddAnAddress('cc', $address, $name);
  597. }
  598. /**
  599. * Adds a "Bcc" address.
  600. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  601. * @param string $address
  602. * @param string $name
  603. * @return boolean true on success, false if address already used
  604. */
  605. public function AddBCC($address, $name = '') {
  606. return $this->AddAnAddress('bcc', $address, $name);
  607. }
  608. /**
  609. * Adds a "Reply-to" address.
  610. * @param string $address
  611. * @param string $name
  612. * @return boolean
  613. */
  614. public function AddReplyTo($address, $name = '') {
  615. return $this->AddAnAddress('Reply-To', $address, $name);
  616. }
  617. /**
  618. * Adds an address to one of the recipient arrays
  619. * Addresses that have been added already return false, but do not throw exceptions
  620. * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
  621. * @param string $address The email address to send to
  622. * @param string $name
  623. * @throws phpmailerException
  624. * @return boolean true on success, false if address already used or invalid in some way
  625. * @access protected
  626. */
  627. protected function AddAnAddress($kind, $address, $name = '') {
  628. if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
  629. $this->SetError($this->Lang('Invalid recipient array').': '.$kind);
  630. if ($this->exceptions) {
  631. throw new phpmailerException('Invalid recipient array: ' . $kind);
  632. }
  633. if ($this->SMTPDebug) {
  634. $this->edebug($this->Lang('Invalid recipient array').': '.$kind);
  635. }
  636. return false;
  637. }
  638. $address = trim($address);
  639. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  640. if (!$this->ValidateAddress($address)) {
  641. $this->SetError($this->Lang('invalid_address').': '. $address);
  642. if ($this->exceptions) {
  643. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  644. }
  645. if ($this->SMTPDebug) {
  646. $this->edebug($this->Lang('invalid_address').': '.$address);
  647. }
  648. return false;
  649. }
  650. if ($kind != 'Reply-To') {
  651. if (!isset($this->all_recipients[strtolower($address)])) {
  652. array_push($this->$kind, array($address, $name));
  653. $this->all_recipients[strtolower($address)] = true;
  654. return true;
  655. }
  656. } else {
  657. if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  658. $this->ReplyTo[strtolower($address)] = array($address, $name);
  659. return true;
  660. }
  661. }
  662. return false;
  663. }
  664. /**
  665. * Set the From and FromName properties
  666. * @param string $address
  667. * @param string $name
  668. * @param boolean $auto Whether to also set the Sender address, defaults to true
  669. * @throws phpmailerException
  670. * @return boolean
  671. */
  672. public function SetFrom($address, $name = '', $auto = true) {
  673. $address = trim($address);
  674. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  675. if (!$this->ValidateAddress($address)) {
  676. $this->SetError($this->Lang('invalid_address').': '. $address);
  677. if ($this->exceptions) {
  678. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  679. }
  680. if ($this->SMTPDebug) {
  681. $this->edebug($this->Lang('invalid_address').': '.$address);
  682. }
  683. return false;
  684. }
  685. $this->From = $address;
  686. $this->FromName = $name;
  687. if ($auto) {
  688. if (empty($this->Sender)) {
  689. $this->Sender = $address;
  690. }
  691. }
  692. return true;
  693. }
  694. /**
  695. * Check that a string looks roughly like an email address should
  696. * Static so it can be used without instantiation, public so people can overload
  697. * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is
  698. * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to
  699. * not allow a@b type valid addresses :(
  700. * @link http://squiloople.com/2009/12/20/email-address-validation/
  701. * @copyright regex Copyright Michael Rushton 2009-10 | http://squiloople.com/ | Feel free to use and redistribute this code. But please keep this copyright notice.
  702. * @param string $address The email address to check
  703. * @return boolean
  704. * @static
  705. * @access public
  706. */
  707. public static function ValidateAddress($address) {
  708. if (defined('PCRE_VERSION')) { //Check this instead of extension_loaded so it works when that function is disabled
  709. if (version_compare(PCRE_VERSION, '8.0') >= 0) {
  710. return (boolean)preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address);
  711. } else {
  712. //Fall back to an older regex that doesn't need a recent PCRE
  713. return (boolean)preg_match('/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD', $address);
  714. }
  715. } else {
  716. //No PCRE! Do something _very_ approximate!
  717. //Check the address is 3 chars or longer and contains an @ that's not the first or last char
  718. return (strlen($address) >= 3 and strpos($address, '@') >= 1 and strpos($address, '@') != strlen($address) - 1);
  719. }
  720. }
  721. /////////////////////////////////////////////////
  722. // METHODS, MAIL SENDING
  723. /////////////////////////////////////////////////
  724. /**
  725. * Creates message and assigns Mailer. If the message is
  726. * not sent successfully then it returns false. Use the ErrorInfo
  727. * variable to view description of the error.
  728. * @throws phpmailerException
  729. * @return bool
  730. */
  731. public function Send() {
  732. try {
  733. if(!$this->PreSend()) return false;
  734. return $this->PostSend();
  735. } catch (phpmailerException $e) {
  736. $this->mailHeader = '';
  737. $this->SetError($e->getMessage());
  738. if ($this->exceptions) {
  739. throw $e;
  740. }
  741. return false;
  742. }
  743. }
  744. /**
  745. * Prep mail by constructing all message entities
  746. * @throws phpmailerException
  747. * @return bool
  748. */
  749. public function PreSend() {
  750. try {
  751. $this->mailHeader = "";
  752. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  753. throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
  754. }
  755. // Set whether the message is multipart/alternative
  756. if(!empty($this->AltBody)) {
  757. $this->ContentType = 'multipart/alternative';
  758. }
  759. $this->error_count = 0; // reset errors
  760. $this->SetMessageType();
  761. //Refuse to send an empty message unless we are specifically allowing it
  762. if (!$this->AllowEmpty and empty($this->Body)) {
  763. throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
  764. }
  765. $this->MIMEHeader = $this->CreateHeader();
  766. $this->MIMEBody = $this->CreateBody();
  767. // To capture the complete message when using mail(), create
  768. // an extra header list which CreateHeader() doesn't fold in
  769. if ($this->Mailer == 'mail') {
  770. if (count($this->to) > 0) {
  771. $this->mailHeader .= $this->AddrAppend("To", $this->to);
  772. } else {
  773. $this->mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;");
  774. }
  775. $this->mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject))));
  776. }
  777. // digitally sign with DKIM if enabled
  778. if (!empty($this->DKIM_domain) && !empty($this->DKIM_private) && !empty($this->DKIM_selector) && !empty($this->DKIM_domain) && file_exists($this->DKIM_private)) {
  779. $header_dkim = $this->DKIM_Add($this->MIMEHeader . $this->mailHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody);
  780. $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader;
  781. }
  782. return true;
  783. } catch (phpmailerException $e) {
  784. $this->SetError($e->getMessage());
  785. if ($this->exceptions) {
  786. throw $e;
  787. }
  788. return false;
  789. }
  790. }
  791. /**
  792. * Actual Email transport function
  793. * Send the email via the selected mechanism
  794. * @throws phpmailerException
  795. * @return bool
  796. */
  797. public function PostSend() {
  798. try {
  799. // Choose the mailer and send through it
  800. switch($this->Mailer) {
  801. case 'sendmail':
  802. return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody);
  803. case 'smtp':
  804. return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);
  805. case 'mail':
  806. return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
  807. case 'amazonses':
  808. return $this->AmazonSESSend($this->MIMEHeader, $this->MIMEBody);
  809. default:
  810. return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
  811. }
  812. } catch (phpmailerException $e) {
  813. $this->SetError($e->getMessage());
  814. if ($this->exceptions) {
  815. throw $e;
  816. }
  817. if ($this->SMTPDebug) {
  818. $this->edebug($e->getMessage()."\n");
  819. }
  820. }
  821. return false;
  822. }
  823. public function AddAmazonSESKey($aws_access_key_id, $aws_secret_key) {
  824. $this->InitiateAmazonSESObject();
  825. $this->amazonses_object->aws_access_key_id = (string)$aws_access_key_id;
  826. $this->amazonses_object->aws_secret_key = (string)$aws_secret_key;
  827. return TRUE;
  828. }
  829. protected function InitiateAmazonSESObject() {
  830. require_once('class.amazonses.php');
  831. if (!isset($this->amazonses_object)) {
  832. $this->amazonses_object = new AmazonSES();
  833. if ($this->amazonses_debug === TRUE)
  834. { $this->amazonses_object->debug = TRUE; }
  835. }
  836. }
  837. protected function AmazonSESSend($header, $body) {
  838. $this->InitiateAmazonSESObject();
  839. $addr_with_name = create_function (
  840. '$addr_ar',
  841. 'return (trim($addr_ar[1]) !== "") ?
  842. "{$addr_ar[1]} <{$addr_ar[0]}>" : $addr_ar[0];'
  843. );
  844. $recipients = array();
  845. foreach (array_merge($this->to, $this->cc, $this->bcc) as $key => $to) {
  846. $recipients[] = ($this->amazonses_use_names === TRUE) ?
  847. $addr_with_name($to) : $to[0];
  848. }
  849. $source = FALSE;
  850. if ($this->amazonses_use_source === TRUE) {
  851. $source = ($this->amazonses_use_names === TRUE) ?
  852. $addr_with_name(array($this->From, $this->FromName)) :
  853. $this->From;
  854. }
  855. $destinations = FALSE;
  856. if ($this->amazonses_use_destinations === TRUE)
  857. { $destinations = $recipients; }
  858. $ret = $this->amazonses_object->send_mail
  859. ($header, $this->Subject, $body, $destinations, $source);
  860. $isSent = ($ret[0] === "200")?1:0;
  861. //print_r($ret);
  862. $this->doCallback($isSent, implode(',', $recipients),
  863. '', '', $this->Subject, $body);
  864. // Everything looks fine.
  865. if ($isSent === 1) {return TRUE; }
  866. // Some sort of error occured.
  867. throw new phpmailerException
  868. ($this->Lang('amazonses_error').$ret[1], self::STOP_CRITICAL);
  869. return FALSE;
  870. }
  871. /**
  872. * Sends mail using the $Sendmail program.
  873. * @param string $header The message headers
  874. * @param string $body The message body
  875. * @throws phpmailerException
  876. * @access protected
  877. * @return bool
  878. */
  879. protected function SendmailSend($header, $body) {
  880. if ($this->Sender != '') {
  881. $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  882. } else {
  883. $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
  884. }
  885. if ($this->SingleTo === true) {
  886. foreach ($this->SingleToArray as $val) {
  887. if(!@$mail = popen($sendmail, 'w')) {
  888. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  889. }
  890. fputs($mail, "To: " . $val . "\n");
  891. fputs($mail, $header);
  892. fputs($mail, $body);
  893. $result = pclose($mail);
  894. // implement call back function if it exists
  895. $isSent = ($result == 0) ? 1 : 0;
  896. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  897. if($result != 0) {
  898. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  899. }
  900. }
  901. } else {
  902. if(!@$mail = popen($sendmail, 'w')) {
  903. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  904. }
  905. fputs($mail, $header);
  906. fputs($mail, $body);
  907. $result = pclose($mail);
  908. // implement call back function if it exists
  909. $isSent = ($result == 0) ? 1 : 0;
  910. $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body);
  911. if($result != 0) {
  912. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  913. }
  914. }
  915. return true;
  916. }
  917. /**
  918. * Sends mail using the PHP mail() function.
  919. * @param string $header The message headers
  920. * @param string $body The message body
  921. * @throws phpmailerException
  922. * @access protected
  923. * @return bool
  924. */
  925. protected function MailSend($header, $body) {
  926. $toArr = array();
  927. foreach($this->to as $t) {
  928. $toArr[] = $this->AddrFormat($t);
  929. }
  930. $to = implode(', ', $toArr);
  931. if (empty($this->Sender)) {
  932. $params = " ";
  933. } else {
  934. $params = sprintf("-f%s", $this->Sender);
  935. }
  936. if ($this->Sender != '' and !ini_get('safe_mode')) {
  937. $old_from = ini_get('sendmail_from');
  938. ini_set('sendmail_from', $this->Sender);
  939. }
  940. $rt = false;
  941. if ($this->SingleTo === true && count($toArr) > 1) {
  942. foreach ($toArr as $val) {
  943. $rt = $this->mail_passthru($val, $this->Subject, $body, $header, $params);
  944. // implement call back function if it exists
  945. $isSent = ($rt == 1) ? 1 : 0;
  946. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  947. }
  948. } else {
  949. $rt = $this->mail_passthru($to, $this->Subject, $body, $header, $params);
  950. // implement call back function if it exists
  951. $isSent = ($rt == 1) ? 1 : 0;
  952. $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
  953. }
  954. if (isset($old_from)) {
  955. ini_set('sendmail_from', $old_from);
  956. }
  957. if(!$rt) {
  958. throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
  959. }
  960. return true;
  961. }
  962. /**
  963. * Sends mail via SMTP using PhpSMTP
  964. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  965. * @param string $header The message headers
  966. * @param string $body The message body
  967. * @throws phpmailerException
  968. * @uses SMTP
  969. * @access protected
  970. * @return bool
  971. */
  972. protected function SmtpSend($header, $body) {
  973. require_once $this->PluginDir . 'class.smtp.php';
  974. $bad_rcpt = array();
  975. if(!$this->SmtpConnect()) {
  976. throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
  977. }
  978. $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
  979. if(!$this->smtp->Mail($smtp_from)) {
  980. $this->SetError($this->Lang('from_failed') . $smtp_from . ' : ' .implode(',', $this->smtp->getError()));
  981. throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
  982. }
  983. // Attempt to send attach all recipients
  984. foreach($this->to as $to) {
  985. if (!$this->smtp->Recipient($to[0])) {
  986. $bad_rcpt[] = $to[0];
  987. // implement call back function if it exists
  988. $isSent = 0;
  989. $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
  990. } else {
  991. // implement call back function if it exists
  992. $isSent = 1;
  993. $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
  994. }
  995. }
  996. foreach($this->cc as $cc) {
  997. if (!$this->smtp->Recipient($cc[0])) {
  998. $bad_rcpt[] = $cc[0];
  999. // implement call back function if it exists
  1000. $isSent = 0;
  1001. $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
  1002. } else {
  1003. // implement call back function if it exists
  1004. $isSent = 1;
  1005. $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
  1006. }
  1007. }
  1008. foreach($this->bcc as $bcc) {
  1009. if (!$this->smtp->Recipient($bcc[0])) {
  1010. $bad_rcpt[] = $bcc[0];
  1011. // implement call back function if it exists
  1012. $isSent = 0;
  1013. $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
  1014. } else {
  1015. // implement call back function if it exists
  1016. $isSent = 1;
  1017. $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
  1018. }
  1019. }
  1020. if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
  1021. $badaddresses = implode(', ', $bad_rcpt);
  1022. throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
  1023. }
  1024. if(!$this->smtp->Data($header . $body)) {
  1025. throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
  1026. }
  1027. if($this->SMTPKeepAlive == true) {
  1028. $this->smtp->Reset();
  1029. } else {
  1030. $this->smtp->Quit();
  1031. $this->smtp->Close();
  1032. }
  1033. return true;
  1034. }
  1035. /**
  1036. * Initiates a connection to an SMTP server.
  1037. * Returns false if the operation failed.
  1038. * @param array $options An array of options compatible with stream_context_create()
  1039. * @uses SMTP
  1040. * @access public
  1041. * @throws phpmailerException
  1042. * @return bool
  1043. */
  1044. public function SmtpConnect($options = array()) {
  1045. if(is_null($this->smtp)) {
  1046. $this->smtp = new SMTP;
  1047. }
  1048. //Already connected?
  1049. if ($this->smtp->Connected()) {
  1050. return true;
  1051. }
  1052. $this->smtp->Timeout = $this->Timeout;
  1053. $this->smtp->do_debug = $this->SMTPDebug;
  1054. $this->smtp->Debugoutput = $this->Debugoutput;
  1055. $this->smtp->do_verp = $this->do_verp;
  1056. $index = 0;
  1057. $tls = ($this->SMTPSecure == 'tls');
  1058. $ssl = ($this->SMTPSecure == 'ssl');
  1059. $hosts = explode(';', $this->Host);
  1060. $lastexception = null;
  1061. foreach ($hosts as $hostentry) {
  1062. $hostinfo = array();
  1063. $host = $hostentry;
  1064. $port = $this->Port;
  1065. if (preg_match('/^(.+):([0-9]+)$/', $hostentry, $hostinfo)) { //If $hostentry contains 'address:port', override default
  1066. $host = $hostinfo[1];
  1067. $port = $hostinfo[2];
  1068. }
  1069. if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout, $options)) {
  1070. try {
  1071. if ($this->Helo) {
  1072. $hello = $this->Helo;
  1073. } else {
  1074. $hello = $this->ServerHostname();
  1075. }
  1076. $this->smtp->Hello($hello);
  1077. if ($tls) {
  1078. if (!$this->smtp->StartTLS()) {
  1079. throw new phpmailerException($this->Lang('connect_host'));
  1080. }
  1081. //We must resend HELO after tls negotiation
  1082. $this->smtp->Hello($hello);
  1083. }
  1084. if ($this->SMTPAuth) {
  1085. if (!$this->smtp->Authenticate($this->Username, $this->Password, $this->AuthType, $this->Realm, $this->Workstation)) {
  1086. throw new phpmailerException($this->Lang('authenticate'));
  1087. }
  1088. }
  1089. return true;
  1090. } catch (phpmailerException $e) {
  1091. $lastexception = $e;
  1092. //We must have connected, but then failed TLS or Auth, so close connection nicely
  1093. $this->smtp->Quit();
  1094. }
  1095. }
  1096. }
  1097. //If we get here, all connection attempts have failed, so close connection hard
  1098. $this->smtp->Close();
  1099. //As we've caught all exceptions, just report whatever the last one was
  1100. if ($this->exceptions and !is_null($lastexception)) {
  1101. throw $lastexception;
  1102. }
  1103. return false;
  1104. }
  1105. /**
  1106. * Closes the active SMTP session if one exists.
  1107. * @return void
  1108. */
  1109. public function SmtpClose() {
  1110. if ($this->smtp !== null) {
  1111. if($this->smtp->Connected()) {
  1112. $this->smtp->Quit();
  1113. $this->smtp->Close();
  1114. }
  1115. }
  1116. }
  1117. /**
  1118. * Sets the language for all class error messages.
  1119. * Returns false if it cannot load the language file. The default language is English.
  1120. * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
  1121. * @param string $lang_path Path to the language file directory
  1122. * @return bool
  1123. * @access public
  1124. */
  1125. function SetLanguage($langcode = 'en', $lang_path = 'language/') {
  1126. //Define full set of translatable strings
  1127. $PHPMAILER_LANG = array(
  1128. 'authenticate' => 'SMTP Error: Could not authenticate.',
  1129. 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  1130. 'data_not_accepted' => 'SMTP Error: Data not accepted.',
  1131. 'empty_message' => 'Message body empty',
  1132. 'encoding' => 'Unknown encoding: ',
  1133. 'execute' => 'Could not execute: ',
  1134. 'file_access' => 'Could not access file: ',
  1135. 'file_open' => 'File Error: Could not open file: ',
  1136. 'from_failed' => 'The following From address failed: ',
  1137. 'instantiate' => 'Could not instantiate mail function.',
  1138. 'invalid_address' => 'Invalid address',
  1139. 'mailer_not_supported' => ' mailer is not supported.',
  1140. 'provide_address' => 'You must provide at least one recipient email address.',
  1141. 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  1142. 'signing' => 'Signing Error: ',
  1143. 'smtp_connect_failed' => 'SMTP Connect() failed.',
  1144. 'smtp_error' => 'SMTP server error: ',
  1145. 'variable_set' => 'Cannot set or reset variable: ',
  1146. 'amazonses_error' => 'AmazonSES Error: '
  1147. );
  1148. //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
  1149. $l = true;
  1150. if ($langcode != 'en') { //There is no English translation file
  1151. $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
  1152. }
  1153. $this->language = $PHPMAILER_LANG;
  1154. return ($l == true); //Returns false if language not found
  1155. }
  1156. /**
  1157. * Return the current array of language strings
  1158. * @return array
  1159. */
  1160. public function GetTranslations() {
  1161. return $this->language;
  1162. }
  1163. /////////////////////////////////////////////////
  1164. // METHODS, MESSAGE CREATION
  1165. /////////////////////////////////////////////////
  1166. /**
  1167. * Creates recipient headers.
  1168. * @access public
  1169. * @param string $type
  1170. * @param array $addr
  1171. * @return string
  1172. */
  1173. public function AddrAppend($type, $addr) {
  1174. $addr_str = $type . ': ';
  1175. $addresses = array();
  1176. foreach ($addr as $a) {
  1177. $addresses[] = $this->AddrFormat($a);
  1178. }
  1179. $addr_str .= implode(', ', $addresses);
  1180. $addr_str .= $this->LE;
  1181. return $addr_str;
  1182. }
  1183. /**
  1184. * Formats an address correctly.
  1185. * @access public
  1186. * @param string $addr
  1187. * @return string
  1188. */
  1189. public function AddrFormat($addr) {
  1190. if (empty($addr[1])) {
  1191. return $this->SecureHeader($addr[0]);
  1192. } else {
  1193. return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
  1194. }
  1195. }
  1196. /**
  1197. * Wraps message for use with mailers that do not
  1198. * automatically perform wrapping and for quoted-printable.
  1199. * Original written by philippe.
  1200. * @param string $message The message to wrap
  1201. * @param integer $length The line length to wrap to
  1202. * @param boolean $qp_mode Whether to run in Quoted-Printable mode
  1203. * @access public
  1204. * @return string
  1205. */
  1206. public function WrapText($message, $length, $qp_mode = false) {
  1207. $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
  1208. // If utf-8 encoding is used, we will need to make sure we don't
  1209. // split multibyte characters when we wrap
  1210. $is_utf8 = (strtolower($this->CharSet) == "utf-8");
  1211. $lelen = strlen($this->LE);
  1212. $crlflen = strlen(self::CRLF);
  1213. $message = $this->FixEOL($message);
  1214. if (substr($message, -$lelen) == $this->LE) {
  1215. $message = substr($message, 0, -$lelen);
  1216. }
  1217. $line = explode($this->LE, $message); // Magic. We know FixEOL uses $LE
  1218. $message = '';
  1219. for ($i = 0 ;$i < count($line); $i++) {
  1220. $line_part = explode(' ', $line[$i]);
  1221. $buf = '';
  1222. for ($e = 0; $e<count($line_part); $e++) {
  1223. $word = $line_part[$e];
  1224. if ($qp_mode and (strlen($word) > $length)) {
  1225. $space_left = $length - strlen($buf) - $crlflen;
  1226. if ($e != 0) {
  1227. if ($space_left > 20) {
  1228. $len = $space_left;
  1229. if ($is_utf8) {
  1230. $len = $this->UTF8CharBoundary($word, $len);
  1231. } elseif (substr($word, $len - 1, 1) == "=") {
  1232. $len--;
  1233. } elseif (substr($word, $len - 2, 1) == "=") {
  1234. $len -= 2;
  1235. }
  1236. $part = substr($word, 0, $len);
  1237. $word = substr($word, $len);
  1238. $buf .= ' ' . $part;
  1239. $message .= $buf . sprintf("=%s", self::CRLF);
  1240. } else {
  1241. $message .= $buf . $soft_break;
  1242. }
  1243. $buf = '';
  1244. }
  1245. while (strlen($word) > 0) {
  1246. if ($length <= 0) {
  1247. break;
  1248. }
  1249. $len = $length;
  1250. if ($is_utf8) {
  1251. $len = $this->UTF8CharBoundary($word, $len);
  1252. } elseif (substr($word, $len - 1, 1) == "=") {
  1253. $len--;
  1254. } elseif (substr($word, $len - 2, 1) == "=") {
  1255. $len -= 2;
  1256. }
  1257. $part = substr($word, 0, $len);
  1258. $word = substr($word, $len);
  1259. if (strlen($word) > 0) {
  1260. $message .= $part . sprintf("=%s", self::CRLF);
  1261. } else {
  1262. $buf = $part;
  1263. }
  1264. }
  1265. } else {
  1266. $buf_o = $buf;
  1267. $buf .= ($e == 0) ? $word : (' ' . $word);
  1268. if (strlen($buf) > $length and $buf_o != '') {
  1269. $message .= $buf_o . $soft_break;
  1270. $buf = $word;
  1271. }
  1272. }
  1273. }
  1274. $message .= $buf . self::CRLF;
  1275. }
  1276. return $message;
  1277. }
  1278. /**
  1279. * Finds last character boundary prior to maxLength in a utf-8
  1280. * quoted (printable) encoded string.
  1281. * Original written by Colin Brown.
  1282. * @access public
  1283. * @param string $encodedText utf-8 QP text
  1284. * @param int $maxLength find last character boundary prior to this length
  1285. * @return int
  1286. */
  1287. public function UTF8CharBoundary($encodedText, $maxLength) {
  1288. $foundSplitPos = false;
  1289. $lookBack = 3;
  1290. while (!$foundSplitPos) {
  1291. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  1292. $encodedCharPos = strpos($lastChunk, "=");
  1293. if ($encodedCharPos !== false) {
  1294. // Found start of encoded character byte within $lookBack block.
  1295. // Check the encoded byte value (the 2 chars after the '=')
  1296. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  1297. $dec = hexdec($hex);
  1298. if ($dec < 128) { // Single byte character.
  1299. // If the encoded char was found at pos 0, it will fit
  1300. // otherwise reduce maxLength to start of the encoded char
  1301. $maxLength = ($encodedCharPos == 0) ? $maxLength :
  1302. $maxLength - ($lookBack - $encodedCharPos);
  1303. $foundSplitPos = true;
  1304. } elseif ($dec >= 192) { // First byte of a multi byte character
  1305. // Reduce maxLength to split at start of character
  1306. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  1307. $foundSplitPos = true;
  1308. } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
  1309. $lookBack += 3;
  1310. }
  1311. } else {
  1312. // No encoded character found
  1313. $foundSplitPos = true;
  1314. }
  1315. }
  1316. return $maxLength;
  1317. }
  1318. /**
  1319. * Set the body wrapping.
  1320. * @access public
  1321. * @return void
  1322. */
  1323. public function SetWordWrap() {
  1324. if($this->WordWrap < 1) {
  1325. return;
  1326. }
  1327. switch($this->message_type) {
  1328. case 'alt':
  1329. case 'alt_inline':
  1330. case 'alt_attach':
  1331. case 'alt_inline_attach':
  1332. $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
  1333. break;
  1334. default:
  1335. $this->Body = $this->WrapText($this->Body, $this->WordWrap);
  1336. break;
  1337. }
  1338. }
  1339. /**
  1340. * Assembles message header.
  1341. * @access public
  1342. * @return string The assembled header
  1343. */
  1344. public function CreateHeader() {
  1345. $result = '';
  1346. // Set the boundaries
  1347. $uniq_id = md5(uniqid(time()));
  1348. $this->boundary[1] = 'b1_' . $uniq_id;
  1349. $this->boundary[2] = 'b2_' . $uniq_id;
  1350. $this->boundary[3] = 'b3_' . $uniq_id;
  1351. if ($this->MessageDate == '') {
  1352. $result .= $this->HeaderLine('Date', self::RFCDate());
  1353. } else {
  1354. $result .= $this->HeaderLine('Date', $this->MessageDate);
  1355. }
  1356. if ($this->ReturnPath) {
  1357. $result .= $this->HeaderLine('Return-Path', '<'.trim($this->ReturnPath).'>');
  1358. } elseif ($this->Sender == '') {
  1359. $result .= $this->HeaderLine('Return-Path', '<'.trim($this->From).'>');
  1360. } else {
  1361. $result .= $this->HeaderLine('Return-Path', '<'.trim($this->Sender).'>');
  1362. }
  1363. // To be created automatically by mail()
  1364. if($this->Mailer != 'mail') {
  1365. if ($this->SingleTo === true) {
  1366. foreach($this->to as $t) {
  1367. $this->SingleToArray[] = $this->AddrFormat($t);
  1368. }
  1369. } else {
  1370. if(count($this->to) > 0) {
  1371. $result .= $this->AddrAppend('To', $this->to);
  1372. } elseif (count($this->cc) == 0) {
  1373. $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
  1374. }
  1375. }
  1376. }
  1377. $from = array();
  1378. $from[0][0] = trim($this->From);
  1379. $from[0][1] = $this->FromName;
  1380. $result .= $this->AddrAppend('From', $from);
  1381. // sendmail and mail() extract Cc from the header before sending
  1382. if(count($this->cc) > 0) {
  1383. $result .= $this->AddrAppend('Cc', $this->cc);
  1384. }
  1385. // sendmail and mail() extract Bcc from the header before sending
  1386. if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
  1387. $result .= $this->AddrAppend('Bcc', $this->bcc);
  1388. }
  1389. if(count($this->ReplyTo) > 0) {
  1390. $result .= $this->AddrAppend('Reply-To', $this->ReplyTo);
  1391. }
  1392. // mail() sets the subject itself
  1393. if($this->Mailer != 'mail') {
  1394. $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
  1395. }
  1396. if($this->MessageID != '') {
  1397. $result .= $this->HeaderLine('Message-ID', $this->MessageID);
  1398. } else {
  1399. $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
  1400. }
  1401. $result .= $this->HeaderLine('X-Priority', $this->Priority);
  1402. if ($this->XMailer == '') {
  1403. $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (https://github.com/PHPMailer/PHPMailer/)');
  1404. } else {
  1405. $myXmailer = trim($this->XMailer);
  1406. if ($myXmailer) {
  1407. $result .= $this->HeaderLine('X-Mailer', $myXmailer);
  1408. }
  1409. }
  1410. if($this->ConfirmReadingTo != '') {
  1411. $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
  1412. }
  1413. // Add custom headers
  1414. for($index = 0; $index < count($this->CustomHeader); $index++) {
  1415. $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
  1416. }
  1417. if (!$this->sign_key_file) {
  1418. if (strpos($result, 'MIME-Version: 1.0') == false) $result .= $this->HeaderLine('MIME-Version', '1.0');
  1419. $result .= $this->GetMailMIME();
  1420. }
  1421. return $result;
  1422. }
  1423. /**
  1424. * Returns the message MIME.
  1425. * @access public
  1426. * @return string
  1427. */
  1428. public function GetMailMIME() {
  1429. $result = '';
  1430. switch($this->message_type) {
  1431. case 'inline':
  1432. $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1433. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"');
  1434. break;
  1435. case 'attach':
  1436. case 'inline_attach':
  1437. case 'alt_attach':
  1438. case 'alt_inline_attach':
  1439. $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
  1440. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"');
  1441. break;
  1442. case 'alt':
  1443. case 'alt_inline':
  1444. $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1445. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"');
  1446. break;
  1447. default:
  1448. // Catches case 'plain': and case '':
  1449. $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset='.$this->CharSet);
  1450. break;
  1451. }
  1452. //RFC1341 part 5 says 7bit is assumed if not specified
  1453. if ($this->Encoding != '7bit') {
  1454. $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
  1455. }
  1456. if($this->Mailer != 'mail') {
  1457. $result .= $this->LE;
  1458. }
  1459. return $result;
  1460. }
  1461. /**
  1462. * Returns the MIME message (headers and body). Only really valid post PreSend().
  1463. * @access public
  1464. * @return string
  1465. */
  1466. public function GetSentMIMEMessage() {
  1467. return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
  1468. }
  1469. /**
  1470. * Assembles the message body. Returns an empty string on failure.
  1471. * @access public
  1472. * @throws phpmailerException
  1473. * @return string The assembled message body
  1474. */
  1475. public function CreateBody() {
  1476. $body = '';
  1477. if ($this->sign_key_file) {
  1478. $body .= $this->GetMailMIME().$this->LE;
  1479. }
  1480. $this->SetWordWrap();
  1481. switch($this->message_type) {
  1482. case 'inline':
  1483. $body .= $this->GetBoundary($this->boundary[1], '', '', '');
  1484. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1485. $body .= $this->LE.$this->LE;
  1486. $body .= $this->AttachAll('inline', $this->boundary[1]);
  1487. break;
  1488. case 'attach':
  1489. $body .= $this->GetBoundary($this->boundary[1], '', '', '');
  1490. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1491. $body .= $this->LE.$this->LE;
  1492. $body .= $this->AttachAll('attachment', $this->boundary[1]);
  1493. break;
  1494. case 'inline_attach':
  1495. $body .= $this->TextLine('--' . $this->boundary[1]);
  1496. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1497. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"');
  1498. $body .= $this->LE;
  1499. $body .= $this->GetBoundary($this->boundary[2], '', '', '');
  1500. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1501. $body .= $this->LE.$this->LE;
  1502. $body .= $this->AttachAll('inline', $this->boundary[2]);
  1503. $body .= $this->LE;
  1504. $body .= $this->AttachAll('attachment', $this->boundary[1]);
  1505. break;
  1506. case 'alt':
  1507. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  1508. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1509. $body .= $this->LE.$this->LE;
  1510. $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
  1511. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1512. $body .= $this->LE.$this->LE;
  1513. if(!empty($this->Ical)) {
  1514. $body .= $this->GetBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
  1515. $body .= $this->EncodeString($this->Ical, $this->Encoding);
  1516. $body .= $this->LE.$this->LE;
  1517. }
  1518. $body .= $this->EndBoundary($this->boundary[1]);
  1519. break;
  1520. case 'alt_inline':
  1521. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  1522. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1523. $body .= $this->LE.$this->LE;
  1524. $body .= $this->TextLine('--' . $this->boundary[1]);
  1525. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1526. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"');
  1527. $body .= $this->LE;
  1528. $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
  1529. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1530. $body .= $this->LE.$this->LE;
  1531. $body .= $this->AttachAll('inline', $this->boundary[2]);
  1532. $body .= $this->LE;
  1533. $body .= $this->EndBoundary($this->boundary[1]);
  1534. break;
  1535. case 'alt_attach':
  1536. $body .= $this->TextLine('--' . $this->boundary[1]);
  1537. $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1538. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"');
  1539. $body .= $this->LE;
  1540. $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
  1541. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1542. $body .= $this->LE.$this->LE;
  1543. $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
  1544. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1545. $body .= $this->LE.$this->LE;
  1546. $body .= $this->EndBoundary($this->boundary[2]);
  1547. $body .= $this->LE;
  1548. $body .= $this->AttachAll('attachment', $this->boundary[1]);
  1549. break;
  1550. case 'alt_inline_attach':
  1551. $body .= $this->TextLine('--' . $this->boundary[1]);
  1552. $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1553. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"');
  1554. $body .= $this->LE;
  1555. $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
  1556. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1557. $body .= $this->LE.$this->LE;
  1558. $body .= $this->TextLine('--' . $this->boundary[2]);
  1559. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1560. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3].'"');
  1561. $body .= $this->LE;
  1562. $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', '');
  1563. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1564. $body .= $this->LE.$this->LE;
  1565. $body .= $this->AttachAll('inline', $this->boundary[3]);
  1566. $body .= $this->LE;
  1567. $body .= $this->EndBoundary($this->boundary[2]);
  1568. $body .= $this->LE;
  1569. $body .= $this->AttachAll('attachment', $this->boundary[1]);
  1570. break;
  1571. default:
  1572. // catch case 'plain' and case ''
  1573. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1574. break;
  1575. }
  1576. if ($this->IsError()) {
  1577. $body = '';
  1578. } elseif ($this->sign_key_file) {
  1579. try {
  1580. if (!defined('PKCS7_TEXT')) {
  1581. throw new phpmailerException($this->Lang('signing').' OpenSSL extension missing.');
  1582. }
  1583. $file = tempnam(sys_get_temp_dir(), 'mail');
  1584. file_put_contents($file, $body); //TODO check this worked
  1585. $signed = tempnam(sys_get_temp_dir(), 'signed');
  1586. if (@openssl_pkcs7_sign($file, $signed, 'file://'.realpath($this->sign_cert_file), array('file://'.realpath($this->sign_key_file), $this->sign_key_pass), null)) {
  1587. @unlink($file);
  1588. $body = file_get_contents($signed);
  1589. @unlink($signed);
  1590. } else {
  1591. @unlink($file);
  1592. @unlink($signed);
  1593. throw new phpmailerException($this->Lang('signing').openssl_error_string());
  1594. }
  1595. } catch (phpmailerException $e) {
  1596. $body = '';
  1597. if ($this->exceptions) {
  1598. throw $e;
  1599. }
  1600. }
  1601. }
  1602. return $body;
  1603. }
  1604. /**
  1605. * Returns the start of a message boundary.
  1606. * @access protected
  1607. * @param string $boundary
  1608. * @param string $charSet
  1609. * @param string $contentType
  1610. * @param string $encoding
  1611. * @return string
  1612. */
  1613. protected function GetBoundary($boundary, $charSet, $contentType, $encoding) {
  1614. $result = '';
  1615. if($charSet == '') {
  1616. $charSet = $this->CharSet;
  1617. }
  1618. if($contentType == '') {
  1619. $contentType = $this->ContentType;
  1620. }
  1621. if($encoding == '') {
  1622. $encoding = $this->Encoding;
  1623. }
  1624. $result .= $this->TextLine('--' . $boundary);
  1625. $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet);
  1626. $result .= $this->LE;
  1627. $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
  1628. $result .= $this->LE;
  1629. return $result;
  1630. }
  1631. /**
  1632. * Returns the end of a message boundary.
  1633. * @access protected
  1634. * @param string $boundary
  1635. * @return string
  1636. */
  1637. protected function EndBoundary($boundary) {
  1638. return $this->LE . '--' . $boundary . '--' . $this->LE;
  1639. }
  1640. /**
  1641. * Sets the message type.
  1642. * @access protected
  1643. * @return void
  1644. */
  1645. protected function SetMessageType() {
  1646. $this->message_type = array();
  1647. if($this->AlternativeExists()) $this->message_type[] = "alt";
  1648. if($this->InlineImageExists()) $this->message_type[] = "inline";
  1649. if($this->AttachmentExists()) $this->message_type[] = "attach";
  1650. $this->message_type = implode("_", $this->message_type);
  1651. if($this->message_type == "") $this->message_type = "plain";
  1652. }
  1653. /**
  1654. * Returns a formatted header line.
  1655. * @access public
  1656. * @param string $name
  1657. * @param string $value
  1658. * @return string
  1659. */
  1660. public function HeaderLine($name, $value) {
  1661. return $name . ': ' . $value . $this->LE;
  1662. }
  1663. /**
  1664. * Returns a formatted mail line.
  1665. * @access public
  1666. * @param string $value
  1667. * @return string
  1668. */
  1669. public function TextLine($value) {
  1670. return $value . $this->LE;
  1671. }
  1672. /////////////////////////////////////////////////
  1673. // CLASS METHODS, ATTACHMENTS
  1674. /////////////////////////////////////////////////
  1675. /**
  1676. * Adds an attachment from a path on the filesystem.
  1677. * Returns false if the file could not be found
  1678. * or accessed.
  1679. * @param string $path Path to the attachment.
  1680. * @param string $name Overrides the attachment name.
  1681. * @param string $encoding File encoding (see $Encoding).
  1682. * @param string $type File extension (MIME) type.
  1683. * @param string $disposition Disposition to use
  1684. * @throws phpmailerException
  1685. * @return bool
  1686. */
  1687. public function AddAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment') {
  1688. try {
  1689. if ( !@is_file($path) ) {
  1690. throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
  1691. }
  1692. //If a MIME type is not specified, try to work it out from the file name
  1693. if ($type == '') {
  1694. $type = self::filenameToType($path);
  1695. }
  1696. $filename = basename($path);
  1697. if ( $name == '' ) {
  1698. $name = $filename;
  1699. }
  1700. $this->attachment[] = array(
  1701. 0 => $path,
  1702. 1 => $filename,
  1703. 2 => $name,
  1704. 3 => $encoding,
  1705. 4 => $type,
  1706. 5 => false, // isStringAttachment
  1707. 6 => $disposition,
  1708. 7 => 0
  1709. );
  1710. } catch (phpmailerException $e) {
  1711. $this->SetError($e->getMessage());
  1712. if ($this->exceptions) {
  1713. throw $e;
  1714. }
  1715. if ($this->SMTPDebug) {
  1716. $this->edebug($e->getMessage()."\n");
  1717. }
  1718. return false;
  1719. }
  1720. return true;
  1721. }
  1722. /**
  1723. * Return the current array of attachments
  1724. * @return array
  1725. */
  1726. public function GetAttachments() {
  1727. return $this->attachment;
  1728. }
  1729. /**
  1730. * Attaches all fs, string, and binary attachments to the message.
  1731. * Returns an empty string on failure.
  1732. * @access protected
  1733. * @param string $disposition_type
  1734. * @param string $boundary
  1735. * @return string
  1736. */
  1737. protected function AttachAll($disposition_type, $boundary) {
  1738. // Return text of body
  1739. $mime = array();
  1740. $cidUniq = array();
  1741. $incl = array();
  1742. // Add all attachments
  1743. foreach ($this->attachment as $attachment) {
  1744. // CHECK IF IT IS A VALID DISPOSITION_FILTER
  1745. if($attachment[6] == $disposition_type) {
  1746. // Check for string attachment
  1747. $string = '';
  1748. $path = '';
  1749. $bString = $attachment[5];
  1750. if ($bString) {
  1751. $string = $attachment[0];
  1752. } else {
  1753. $path = $attachment[0];
  1754. }
  1755. $inclhash = md5(serialize($attachment));
  1756. if (in_array($inclhash, $incl)) { continue; }
  1757. $incl[] = $inclhash;
  1758. $filename = $attachment[1];
  1759. $name = $attachment[2];
  1760. $encoding = $attachment[3];
  1761. $type = $attachment[4];
  1762. $disposition = $attachment[6];
  1763. $cid = $attachment[7];
  1764. if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
  1765. $cidUniq[$cid] = true;
  1766. $mime[] = sprintf("--%s%s", $boundary, $this->LE);
  1767. $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
  1768. $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
  1769. if($disposition == 'inline') {
  1770. $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
  1771. }
  1772. //If a filename contains any of these chars, it should be quoted, but not otherwise: RFC2183 & RFC2045 5.1
  1773. //Fixes a warning in IETF's msglint MIME checker
  1774. //
  1775. // Allow for bypassing the Content-Disposition header totally
  1776. if (!(empty($disposition))) {
  1777. if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $name)) {
  1778. $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
  1779. } else {
  1780. $mime[] = sprintf("Content-Disposition: %s; filename=%s%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
  1781. }
  1782. } else {
  1783. $mime[] = $this->LE;
  1784. }
  1785. // Encode as string attachment
  1786. if($bString) {
  1787. $mime[] = $this->EncodeString($string, $encoding);
  1788. if($this->IsError()) {
  1789. return '';
  1790. }
  1791. $mime[] = $this->LE.$this->LE;
  1792. } else {
  1793. $mime[] = $this->EncodeFile($path, $encoding);
  1794. if($this->IsError()) {
  1795. return '';
  1796. }
  1797. $mime[] = $this->LE.$this->LE;
  1798. }
  1799. }
  1800. }
  1801. $mime[] = sprintf("--%s--%s", $boundary, $this->LE);
  1802. return implode("", $mime);
  1803. }
  1804. /**
  1805. * Encodes attachment in requested format.
  1806. * Returns an empty string on failure.
  1807. * @param string $path The full path to the file
  1808. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1809. * @throws phpmailerException
  1810. * @see EncodeFile()
  1811. * @access protected
  1812. * @return string
  1813. */
  1814. protected function EncodeFile($path, $encoding = 'base64') {
  1815. try {
  1816. if (!is_readable($path)) {
  1817. throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
  1818. }
  1819. $magic_quotes = get_magic_quotes_runtime();
  1820. if ($magic_quotes) {
  1821. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  1822. set_magic_quotes_runtime(0);
  1823. } else {
  1824. ini_set('magic_quotes_runtime', 0);
  1825. }
  1826. }
  1827. $file_buffer = file_get_contents($path);
  1828. $file_buffer = $this->EncodeString($file_buffer, $encoding);
  1829. if ($magic_quotes) {
  1830. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  1831. set_magic_quotes_runtime($magic_quotes);
  1832. } else {
  1833. ini_set('magic_quotes_runtime', $magic_quotes);
  1834. }
  1835. }
  1836. return $file_buffer;
  1837. } catch (Exception $e) {
  1838. $this->SetError($e->getMessage());
  1839. return '';
  1840. }
  1841. }
  1842. /**
  1843. * Encodes string to requested format.
  1844. * Returns an empty string on failure.
  1845. * @param string $str The text to encode
  1846. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1847. * @access public
  1848. * @return string
  1849. */
  1850. public function EncodeString($str, $encoding = 'base64') {
  1851. $encoded = '';
  1852. switch(strtolower($encoding)) {
  1853. case 'base64':
  1854. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  1855. break;
  1856. case '7bit':
  1857. case '8bit':
  1858. $encoded = $this->FixEOL($str);
  1859. //Make sure it ends with a line break
  1860. if (substr($encoded, -(strlen($this->LE))) != $this->LE)
  1861. $encoded .= $this->LE;
  1862. break;
  1863. case 'binary':
  1864. $encoded = $str;
  1865. break;
  1866. case 'quoted-printable':
  1867. $encoded = $this->EncodeQP($str);
  1868. break;
  1869. default:
  1870. $this->SetError($this->Lang('encoding') . $encoding);
  1871. break;
  1872. }
  1873. return $encoded;
  1874. }
  1875. /**
  1876. * Encode a header string to best (shortest) of Q, B, quoted or none.
  1877. * @access public
  1878. * @param string $str
  1879. * @param string $position
  1880. * @return string
  1881. */
  1882. public function EncodeHeader($str, $position = 'text') {
  1883. $x = 0;
  1884. switch (strtolower($position)) {
  1885. case 'phrase':
  1886. if (!preg_match('/[\200-\377]/', $str)) {
  1887. // Can't use addslashes as we don't know what value has magic_quotes_sybase
  1888. $encoded = addcslashes($str, "\0..\37\177\\\"");
  1889. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  1890. return ($encoded);
  1891. } else {
  1892. return ("\"$encoded\"");
  1893. }
  1894. }
  1895. $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  1896. break;
  1897. case 'comment':
  1898. $x = preg_match_all('/[()"]/', $str, $matches);
  1899. // Fall-through
  1900. case 'text':
  1901. default:
  1902. $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  1903. break;
  1904. }
  1905. if ($x == 0) { //There are no chars that need encoding
  1906. return ($str);
  1907. }
  1908. $maxlen = 75 - 7 - strlen($this->CharSet);
  1909. // Try to select the encoding which should produce the shortest output
  1910. if ($x > strlen($str)/3) { //More than a third of the content will need encoding, so B encoding will be most efficient
  1911. $encoding = 'B';
  1912. if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
  1913. // Use a custom function which correctly encodes and wraps long
  1914. // multibyte strings without breaking lines within a character
  1915. $encoded = $this->Base64EncodeWrapMB($str, "\n");
  1916. } else {
  1917. $encoded = base64_encode($str);
  1918. $maxlen -= $maxlen % 4;
  1919. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  1920. }
  1921. } else {
  1922. $encoding = 'Q';
  1923. $encoded = $this->EncodeQ($str, $position);
  1924. $encoded = $this->WrapText($encoded, $maxlen, true);
  1925. $encoded = str_replace('='.self::CRLF, "\n", trim($encoded));
  1926. }
  1927. $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
  1928. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  1929. return $encoded;
  1930. }
  1931. /**
  1932. * Checks if a string contains multibyte characters.
  1933. * @access public
  1934. * @param string $str multi-byte text to wrap encode
  1935. * @return bool
  1936. */
  1937. public function HasMultiBytes($str) {
  1938. if (function_exists('mb_strlen')) {
  1939. return (strlen($str) > mb_strlen($str, $this->CharSet));
  1940. } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  1941. return false;
  1942. }
  1943. }
  1944. /**
  1945. * Correctly encodes and wraps long multibyte strings for mail headers
  1946. * without breaking lines within a character.
  1947. * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
  1948. * @access public
  1949. * @param string $str multi-byte text to wrap encode
  1950. * @param string $lf string to use as linefeed/end-of-line
  1951. * @return string
  1952. */
  1953. public function Base64EncodeWrapMB($str, $lf=null) {
  1954. $start = "=?".$this->CharSet."?B?";
  1955. $end = "?=";
  1956. $encoded = "";
  1957. if ($lf === null) {
  1958. $lf = $this->LE;
  1959. }
  1960. $mb_length = mb_strlen($str, $this->CharSet);
  1961. // Each line must have length <= 75, including $start and $end
  1962. $length = 75 - strlen($start) - strlen($end);
  1963. // Average multi-byte ratio
  1964. $ratio = $mb_length / strlen($str);
  1965. // Base64 has a 4:3 ratio
  1966. $offset = $avgLength = floor($length * $ratio * .75);
  1967. for ($i = 0; $i < $mb_length; $i += $offset) {
  1968. $lookBack = 0;
  1969. do {
  1970. $offset = $avgLength - $lookBack;
  1971. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  1972. $chunk = base64_encode($chunk);
  1973. $lookBack++;
  1974. }
  1975. while (strlen($chunk) > $length);
  1976. $encoded .= $chunk . $lf;
  1977. }
  1978. // Chomp the last linefeed
  1979. $encoded = substr($encoded, 0, -strlen($lf));
  1980. return $encoded;
  1981. }
  1982. /**
  1983. * Encode string to RFC2045 (6.7) quoted-printable format
  1984. * @access public
  1985. * @param string $string The text to encode
  1986. * @param integer $line_max Number of chars allowed on a line before wrapping
  1987. * @return string
  1988. * @link PHP version adapted from http://www.php.net/manual/en/function.quoted-printable-decode.php#89417
  1989. */
  1990. public function EncodeQP($string, $line_max = 76) {
  1991. if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
  1992. return quoted_printable_encode($string);
  1993. }
  1994. //Fall back to a pure PHP implementation
  1995. $string = str_replace(array('%20', '%0D%0A.', '%0D%0A', '%'), array(' ', "\r\n=2E", "\r\n", '='), rawurlencode($string));
  1996. $string = preg_replace('/[^\r\n]{'.($line_max - 3).'}[^=\r\n]{2}/', "$0=\r\n", $string);
  1997. return $string;
  1998. }
  1999. /**
  2000. * Wrapper to preserve BC for old QP encoding function that was removed
  2001. * @see EncodeQP()
  2002. * @access public
  2003. * @param string $string
  2004. * @param integer $line_max
  2005. * @param bool $space_conv
  2006. * @return string
  2007. */
  2008. public function EncodeQPphp($string, $line_max = 76, $space_conv = false) {
  2009. return $this->EncodeQP($string, $line_max);
  2010. }
  2011. /**
  2012. * Encode string to q encoding.
  2013. * @link http://tools.ietf.org/html/rfc2047
  2014. * @param string $str the text to encode
  2015. * @param string $position Where the text is going to be used, see the RFC for what that means
  2016. * @access public
  2017. * @return string
  2018. */
  2019. public function EncodeQ($str, $position = 'text') {
  2020. //There should not be any EOL in the string
  2021. $pattern = '';
  2022. $encoded = str_replace(array("\r", "\n"), '', $str);
  2023. switch (strtolower($position)) {
  2024. case 'phrase':
  2025. $pattern = '^A-Za-z0-9!*+\/ -';
  2026. break;
  2027. case 'comment':
  2028. $pattern = '\(\)"';
  2029. //note that we don't break here!
  2030. //for this reason we build the $pattern without including delimiters and []
  2031. case 'text':
  2032. default:
  2033. //Replace every high ascii, control =, ? and _ characters
  2034. //We put \075 (=) as first value to make sure it's the first one in being converted, preventing double encode
  2035. $pattern = '\075\000-\011\013\014\016-\037\077\137\177-\377' . $pattern;
  2036. break;
  2037. }
  2038. if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
  2039. foreach (array_unique($matches[0]) as $char) {
  2040. $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  2041. }
  2042. }
  2043. //Replace every spaces to _ (more readable than =20)
  2044. return str_replace(' ', '_', $encoded);
  2045. }
  2046. /**
  2047. * Adds a string or binary attachment (non-filesystem) to the list.
  2048. * This method can be used to attach ascii or binary data,
  2049. * such as a BLOB record from a database.
  2050. * @param string $string String attachment data.
  2051. * @param string $filename Name of the attachment.
  2052. * @param string $encoding File encoding (see $Encoding).
  2053. * @param string $type File extension (MIME) type.
  2054. * @param string $disposition Disposition to use
  2055. * @return void
  2056. */
  2057. public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = '', $disposition = 'attachment') {
  2058. //If a MIME type is not specified, try to work it out from the file name
  2059. if ($type == '') {
  2060. $type = self::filenameToType($filename);
  2061. }
  2062. // Append to $attachment array
  2063. $this->attachment[] = array(
  2064. 0 => $string,
  2065. 1 => $filename,
  2066. 2 => basename($filename),
  2067. 3 => $encoding,
  2068. 4 => $type,
  2069. 5 => true, // isStringAttachment
  2070. 6 => $disposition,
  2071. 7 => 0
  2072. );
  2073. }
  2074. /**
  2075. * Add an embedded attachment from a file.
  2076. * This can include images, sounds, and just about any other document type.
  2077. * @param string $path Path to the attachment.
  2078. * @param string $cid Content ID of the attachment; Use this to reference
  2079. * the content when using an embedded image in HTML.
  2080. * @param string $name Overrides the attachment name.
  2081. * @param string $encoding File encoding (see $Encoding).
  2082. * @param string $type File MIME type.
  2083. * @param string $disposition Disposition to use
  2084. * @return bool True on successfully adding an attachment
  2085. */
  2086. public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline') {
  2087. if ( !@is_file($path) ) {
  2088. $this->SetError($this->Lang('file_access') . $path);
  2089. return false;
  2090. }
  2091. //If a MIME type is not specified, try to work it out from the file name
  2092. if ($type == '') {
  2093. $type = self::filenameToType($path);
  2094. }
  2095. $filename = basename($path);
  2096. if ( $name == '' ) {
  2097. $name = $filename;
  2098. }
  2099. // Append to $attachment array
  2100. $this->attachment[] = array(
  2101. 0 => $path,
  2102. 1 => $filename,
  2103. 2 => $name,
  2104. 3 => $encoding,
  2105. 4 => $type,
  2106. 5 => false, // isStringAttachment
  2107. 6 => $disposition,
  2108. 7 => $cid
  2109. );
  2110. return true;
  2111. }
  2112. /**
  2113. * Add an embedded stringified attachment.
  2114. * This can include images, sounds, and just about any other document type.
  2115. * Be sure to set the $type to an image type for images:
  2116. * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
  2117. * @param string $string The attachment binary data.
  2118. * @param string $cid Content ID of the attachment; Use this to reference
  2119. * the content when using an embedded image in HTML.
  2120. * @param string $name
  2121. * @param string $encoding File encoding (see $Encoding).
  2122. * @param string $type MIME type.
  2123. * @param string $disposition Disposition to use
  2124. * @return bool True on successfully adding an attachment
  2125. */
  2126. public function AddStringEmbeddedImage($string, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline') {
  2127. //If a MIME type is not specified, try to work it out from the name
  2128. if ($type == '') {
  2129. $type = self::filenameToType($name);
  2130. }
  2131. // Append to $attachment array
  2132. $this->attachment[] = array(
  2133. 0 => $string,
  2134. 1 => $name,
  2135. 2 => $name,
  2136. 3 => $encoding,
  2137. 4 => $type,
  2138. 5 => true, // isStringAttachment
  2139. 6 => $disposition,
  2140. 7 => $cid
  2141. );
  2142. return true;
  2143. }
  2144. /**
  2145. * Returns true if an inline attachment is present.
  2146. * @access public
  2147. * @return bool
  2148. */
  2149. public function InlineImageExists() {
  2150. foreach($this->attachment as $attachment) {
  2151. if ($attachment[6] == 'inline') {
  2152. return true;
  2153. }
  2154. }
  2155. return false;
  2156. }
  2157. /**
  2158. * Returns true if an attachment (non-inline) is present.
  2159. * @return bool
  2160. */
  2161. public function AttachmentExists() {
  2162. foreach($this->attachment as $attachment) {
  2163. if ($attachment[6] == 'attachment') {
  2164. return true;
  2165. }
  2166. }
  2167. return false;
  2168. }
  2169. /**
  2170. * Does this message have an alternative body set?
  2171. * @return bool
  2172. */
  2173. public function AlternativeExists() {
  2174. return !empty($this->AltBody);
  2175. }
  2176. /////////////////////////////////////////////////
  2177. // CLASS METHODS, MESSAGE RESET
  2178. /////////////////////////////////////////////////
  2179. /**
  2180. * Clears all recipients assigned in the TO array. Returns void.
  2181. * @return void
  2182. */
  2183. public function ClearAddresses() {
  2184. foreach($this->to as $to) {
  2185. unset($this->all_recipients[strtolower($to[0])]);
  2186. }
  2187. $this->to = array();
  2188. }
  2189. /**
  2190. * Clears all recipients assigned in the CC array. Returns void.
  2191. * @return void
  2192. */
  2193. public function ClearCCs() {
  2194. foreach($this->cc as $cc) {
  2195. unset($this->all_recipients[strtolower($cc[0])]);
  2196. }
  2197. $this->cc = array();
  2198. }
  2199. /**
  2200. * Clears all recipients assigned in the BCC array. Returns void.
  2201. * @return void
  2202. */
  2203. public function ClearBCCs() {
  2204. foreach($this->bcc as $bcc) {
  2205. unset($this->all_recipients[strtolower($bcc[0])]);
  2206. }
  2207. $this->bcc = array();
  2208. }
  2209. /**
  2210. * Clears all recipients assigned in the ReplyTo array. Returns void.
  2211. * @return void
  2212. */
  2213. public function ClearReplyTos() {
  2214. $this->ReplyTo = array();
  2215. }
  2216. /**
  2217. * Clears all recipients assigned in the TO, CC and BCC
  2218. * array. Returns void.
  2219. * @return void
  2220. */
  2221. public function ClearAllRecipients() {
  2222. $this->to = array();
  2223. $this->cc = array();
  2224. $this->bcc = array();
  2225. $this->all_recipients = array();
  2226. }
  2227. /**
  2228. * Clears all previously set filesystem, string, and binary
  2229. * attachments. Returns void.
  2230. * @return void
  2231. */
  2232. public function ClearAttachments() {
  2233. $this->attachment = array();
  2234. }
  2235. /**
  2236. * Clears all custom headers. Returns void.
  2237. * @return void
  2238. */
  2239. public function ClearCustomHeaders() {
  2240. $this->CustomHeader = array();
  2241. }
  2242. /////////////////////////////////////////////////
  2243. // CLASS METHODS, MISCELLANEOUS
  2244. /////////////////////////////////////////////////
  2245. /**
  2246. * Adds the error message to the error container.
  2247. * @access protected
  2248. * @param string $msg
  2249. * @return void
  2250. */
  2251. protected function SetError($msg) {
  2252. $this->error_count++;
  2253. if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  2254. $lasterror = $this->smtp->getError();
  2255. if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
  2256. $msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
  2257. }
  2258. }
  2259. $this->ErrorInfo = $msg;
  2260. }
  2261. /**
  2262. * Returns the proper RFC 822 formatted date.
  2263. * @access public
  2264. * @return string
  2265. * @static
  2266. */
  2267. public static function RFCDate() {
  2268. //Set the time zone to whatever the default is to avoid 500 errors
  2269. //Will default to UTC if it's not set properly in php.ini
  2270. date_default_timezone_set(@date_default_timezone_get());
  2271. return date('D, j M Y H:i:s O');
  2272. }
  2273. /**
  2274. * Returns the server hostname or 'localhost.localdomain' if unknown.
  2275. * @access protected
  2276. * @return string
  2277. */
  2278. protected function ServerHostname() {
  2279. if (!empty($this->Hostname)) {
  2280. $result = $this->Hostname;
  2281. } elseif (isset($_SERVER['SERVER_NAME'])) {
  2282. $result = $_SERVER['SERVER_NAME'];
  2283. } else {
  2284. $result = 'localhost.localdomain';
  2285. }
  2286. return $result;
  2287. }
  2288. /**
  2289. * Returns a message in the appropriate language.
  2290. * @access protected
  2291. * @param string $key
  2292. * @return string
  2293. */
  2294. protected function Lang($key) {
  2295. if(count($this->language) < 1) {
  2296. $this->SetLanguage('en'); // set the default language
  2297. }
  2298. if(isset($this->language[$key])) {
  2299. return $this->language[$key];
  2300. } else {
  2301. return 'Language string failed to load: ' . $key;
  2302. }
  2303. }
  2304. /**
  2305. * Returns true if an error occurred.
  2306. * @access public
  2307. * @return bool
  2308. */
  2309. public function IsError() {
  2310. return ($this->error_count > 0);
  2311. }
  2312. /**
  2313. * Changes every end of line from CRLF, CR or LF to $this->LE.
  2314. * @access public
  2315. * @param string $str String to FixEOL
  2316. * @return string
  2317. */
  2318. public function FixEOL($str) {
  2319. // condense down to \n
  2320. $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
  2321. // Now convert LE as needed
  2322. if ($this->LE !== "\n") {
  2323. $nstr = str_replace("\n", $this->LE, $nstr);
  2324. }
  2325. return $nstr;
  2326. }
  2327. /**
  2328. * Adds a custom header. $name value can be overloaded to contain
  2329. * both header name and value (name:value)
  2330. * @access public
  2331. * @param string $name custom header name
  2332. * @param string $value header value
  2333. * @return void
  2334. */
  2335. public function AddCustomHeader($name, $value=null) {
  2336. if ($value === null) {
  2337. // Value passed in as name:value
  2338. $this->CustomHeader[] = explode(':', $name, 2);
  2339. } else {
  2340. $this->CustomHeader[] = array($name, $value);
  2341. }
  2342. }
  2343. /**
  2344. * Creates a message from an HTML string, making modifications for inline images and backgrounds
  2345. * and creates a plain-text version by converting the HTML
  2346. * Overwrites any existing values in $this->Body and $this->AltBody
  2347. * @access public
  2348. * @param string $message HTML message string
  2349. * @param string $basedir baseline directory for path
  2350. * @param bool $advanced Whether to use the advanced HTML to text converter
  2351. * @return string $message
  2352. */
  2353. public function MsgHTML($message, $basedir = '', $advanced = false) {
  2354. preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images);
  2355. if (isset($images[2])) {
  2356. foreach ($images[2] as $i => $url) {
  2357. // do not change urls for absolute images (thanks to corvuscorax)
  2358. if (!preg_match('#^[A-z]+://#', $url)) {
  2359. $filename = basename($url);
  2360. $directory = dirname($url);
  2361. if ($directory == '.') {
  2362. $directory = '';
  2363. }
  2364. $cid = md5($url).'@phpmailer.0'; //RFC2392 S 2
  2365. if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
  2366. $basedir .= '/';
  2367. }
  2368. if (strlen($directory) > 1 && substr($directory, -1) != '/') {
  2369. $directory .= '/';
  2370. }
  2371. if ($this->AddEmbeddedImage($basedir.$directory.$filename, $cid, $filename, 'base64', self::_mime_types(self::mb_pathinfo($filename, PATHINFO_EXTENSION)))) {
  2372. $message = preg_replace("/".$images[1][$i]."=[\"']".preg_quote($url, '/')."[\"']/Ui", $images[1][$i]."=\"cid:".$cid."\"", $message);
  2373. }
  2374. }
  2375. }
  2376. }
  2377. $this->IsHTML(true);
  2378. if (empty($this->AltBody)) {
  2379. $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
  2380. }
  2381. //Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
  2382. $this->Body = $this->NormalizeBreaks($message);
  2383. $this->AltBody = $this->NormalizeBreaks($this->html2text($message, $advanced));
  2384. return $this->Body;
  2385. }
  2386. /**
  2387. * Convert an HTML string into a plain text version
  2388. * @param string $html The HTML text to convert
  2389. * @param bool $advanced Should this use the more complex html2text converter or just a simple one?
  2390. * @return string
  2391. */
  2392. public function html2text($html, $advanced = false) {
  2393. if ($advanced) {
  2394. require_once 'extras/class.html2text.php';
  2395. $h = new html2text($html);
  2396. return $h->get_text();
  2397. }
  2398. return html_entity_decode(trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), ENT_QUOTES, $this->CharSet);
  2399. }
  2400. /**
  2401. * Gets the MIME type of the embedded or inline image
  2402. * @param string $ext File extension
  2403. * @access public
  2404. * @return string MIME type of ext
  2405. * @static
  2406. */
  2407. public static function _mime_types($ext = '') {
  2408. $mimes = array(
  2409. 'xl' => 'application/excel',
  2410. 'hqx' => 'application/mac-binhex40',
  2411. 'cpt' => 'application/mac-compactpro',
  2412. 'bin' => 'application/macbinary',
  2413. 'doc' => 'application/msword',
  2414. 'word' => 'application/msword',
  2415. 'class' => 'application/octet-stream',
  2416. 'dll' => 'application/octet-stream',
  2417. 'dms' => 'application/octet-stream',
  2418. 'exe' => 'application/octet-stream',
  2419. 'lha' => 'application/octet-stream',
  2420. 'lzh' => 'application/octet-stream',
  2421. 'psd' => 'application/octet-stream',
  2422. 'sea' => 'application/octet-stream',
  2423. 'so' => 'application/octet-stream',
  2424. 'oda' => 'application/oda',
  2425. 'pdf' => 'application/pdf',
  2426. 'ai' => 'application/postscript',
  2427. 'eps' => 'application/postscript',
  2428. 'ps' => 'application/postscript',
  2429. 'smi' => 'application/smil',
  2430. 'smil' => 'application/smil',
  2431. 'mif' => 'application/vnd.mif',
  2432. 'xls' => 'application/vnd.ms-excel',
  2433. 'ppt' => 'application/vnd.ms-powerpoint',
  2434. 'wbxml' => 'application/vnd.wap.wbxml',
  2435. 'wmlc' => 'application/vnd.wap.wmlc',
  2436. 'dcr' => 'application/x-director',
  2437. 'dir' => 'application/x-director',
  2438. 'dxr' => 'application/x-director',
  2439. 'dvi' => 'application/x-dvi',
  2440. 'gtar' => 'application/x-gtar',
  2441. 'php3' => 'application/x-httpd-php',
  2442. 'php4' => 'application/x-httpd-php',
  2443. 'php' => 'application/x-httpd-php',
  2444. 'phtml' => 'application/x-httpd-php',
  2445. 'phps' => 'application/x-httpd-php-source',
  2446. 'js' => 'application/x-javascript',
  2447. 'swf' => 'application/x-shockwave-flash',
  2448. 'sit' => 'application/x-stuffit',
  2449. 'tar' => 'application/x-tar',
  2450. 'tgz' => 'application/x-tar',
  2451. 'xht' => 'application/xhtml+xml',
  2452. 'xhtml' => 'application/xhtml+xml',
  2453. 'zip' => 'application/zip',
  2454. 'mid' => 'audio/midi',
  2455. 'midi' => 'audio/midi',
  2456. 'mp2' => 'audio/mpeg',
  2457. 'mp3' => 'audio/mpeg',
  2458. 'mpga' => 'audio/mpeg',
  2459. 'aif' => 'audio/x-aiff',
  2460. 'aifc' => 'audio/x-aiff',
  2461. 'aiff' => 'audio/x-aiff',
  2462. 'ram' => 'audio/x-pn-realaudio',
  2463. 'rm' => 'audio/x-pn-realaudio',
  2464. 'rpm' => 'audio/x-pn-realaudio-plugin',
  2465. 'ra' => 'audio/x-realaudio',
  2466. 'wav' => 'audio/x-wav',
  2467. 'bmp' => 'image/bmp',
  2468. 'gif' => 'image/gif',
  2469. 'jpeg' => 'image/jpeg',
  2470. 'jpe' => 'image/jpeg',
  2471. 'jpg' => 'image/jpeg',
  2472. 'png' => 'image/png',
  2473. 'tiff' => 'image/tiff',
  2474. 'tif' => 'image/tiff',
  2475. 'eml' => 'message/rfc822',
  2476. 'css' => 'text/css',
  2477. 'html' => 'text/html',
  2478. 'htm' => 'text/html',
  2479. 'shtml' => 'text/html',
  2480. 'log' => 'text/plain',
  2481. 'text' => 'text/plain',
  2482. 'txt' => 'text/plain',
  2483. 'rtx' => 'text/richtext',
  2484. 'rtf' => 'text/rtf',
  2485. 'xml' => 'text/xml',
  2486. 'xsl' => 'text/xml',
  2487. 'mpeg' => 'video/mpeg',
  2488. 'mpe' => 'video/mpeg',
  2489. 'mpg' => 'video/mpeg',
  2490. 'mov' => 'video/quicktime',
  2491. 'qt' => 'video/quicktime',
  2492. 'rv' => 'video/vnd.rn-realvideo',
  2493. 'avi' => 'video/x-msvideo',
  2494. 'movie' => 'video/x-sgi-movie'
  2495. );
  2496. return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
  2497. }
  2498. /**
  2499. * Try to map a file name to a MIME type, default to application/octet-stream
  2500. * @param string $filename A file name or full path, does not need to exist as a file
  2501. * @return string
  2502. * @static
  2503. */
  2504. public static function filenameToType($filename) {
  2505. //In case the path is a URL, strip any query string before getting extension
  2506. $qpos = strpos($filename, '?');
  2507. if ($qpos !== false) {
  2508. $filename = substr($filename, 0, $qpos);
  2509. }
  2510. $pathinfo = self::mb_pathinfo($filename);
  2511. return self::_mime_types($pathinfo['extension']);
  2512. }
  2513. /**
  2514. * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe.
  2515. * Works similarly to the one in PHP >= 5.2.0
  2516. * @link http://www.php.net/manual/en/function.pathinfo.php#107461
  2517. * @param string $path A filename or path, does not need to exist as a file
  2518. * @param integer|string $options Either a PATHINFO_* constant, or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2
  2519. * @return string|array
  2520. * @static
  2521. */
  2522. public static function mb_pathinfo($path, $options = null) {
  2523. $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
  2524. $m = array();
  2525. preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $m);
  2526. if(array_key_exists(1, $m)) {
  2527. $ret['dirname'] = $m[1];
  2528. }
  2529. if(array_key_exists(2, $m)) {
  2530. $ret['basename'] = $m[2];
  2531. }
  2532. if(array_key_exists(5, $m)) {
  2533. $ret['extension'] = $m[5];
  2534. }
  2535. if(array_key_exists(3, $m)) {
  2536. $ret['filename'] = $m[3];
  2537. }
  2538. switch($options) {
  2539. case PATHINFO_DIRNAME:
  2540. case 'dirname':
  2541. return $ret['dirname'];
  2542. break;
  2543. case PATHINFO_BASENAME:
  2544. case 'basename':
  2545. return $ret['basename'];
  2546. break;
  2547. case PATHINFO_EXTENSION:
  2548. case 'extension':
  2549. return $ret['extension'];
  2550. break;
  2551. case PATHINFO_FILENAME:
  2552. case 'filename':
  2553. return $ret['filename'];
  2554. break;
  2555. default:
  2556. return $ret;
  2557. }
  2558. }
  2559. /**
  2560. * Set (or reset) Class Objects (variables)
  2561. *
  2562. * Usage Example:
  2563. * $page->set('X-Priority', '3');
  2564. *
  2565. * @access public
  2566. * @param string $name
  2567. * @param mixed $value
  2568. * NOTE: will not work with arrays, there are no arrays to set/reset
  2569. * @throws phpmailerException
  2570. * @return bool
  2571. * @todo Should this not be using __set() magic function?
  2572. */
  2573. public function set($name, $value = '') {
  2574. try {
  2575. if (isset($this->$name) ) {
  2576. $this->$name = $value;
  2577. } else {
  2578. throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL);
  2579. }
  2580. } catch (Exception $e) {
  2581. $this->SetError($e->getMessage());
  2582. if ($e->getCode() == self::STOP_CRITICAL) {
  2583. return false;
  2584. }
  2585. }
  2586. return true;
  2587. }
  2588. /**
  2589. * Strips newlines to prevent header injection.
  2590. * @access public
  2591. * @param string $str
  2592. * @return string
  2593. */
  2594. public function SecureHeader($str) {
  2595. return trim(str_replace(array("\r", "\n"), '', $str));
  2596. }
  2597. /**
  2598. * Normalize UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format
  2599. * Defaults to CRLF (for message bodies) and preserves consecutive breaks
  2600. * @param string $text
  2601. * @param string $breaktype What kind of line break to use, defaults to CRLF
  2602. * @return string
  2603. * @access public
  2604. * @static
  2605. */
  2606. public static function NormalizeBreaks($text, $breaktype = "\r\n") {
  2607. return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
  2608. }
  2609. /**
  2610. * Set the private key file and password to sign the message.
  2611. *
  2612. * @access public
  2613. * @param string $cert_filename
  2614. * @param string $key_filename
  2615. * @param string $key_pass Password for private key
  2616. */
  2617. public function Sign($cert_filename, $key_filename, $key_pass) {
  2618. $this->sign_cert_file = $cert_filename;
  2619. $this->sign_key_file = $key_filename;
  2620. $this->sign_key_pass = $key_pass;
  2621. }
  2622. /**
  2623. * Set the private key file and password to sign the message.
  2624. *
  2625. * @access public
  2626. * @param string $txt
  2627. * @return string
  2628. */
  2629. public function DKIM_QP($txt) {
  2630. $line = '';
  2631. for ($i = 0; $i < strlen($txt); $i++) {
  2632. $ord = ord($txt[$i]);
  2633. if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
  2634. $line .= $txt[$i];
  2635. } else {
  2636. $line .= "=".sprintf("%02X", $ord);
  2637. }
  2638. }
  2639. return $line;
  2640. }
  2641. /**
  2642. * Generate DKIM signature
  2643. *
  2644. * @access public
  2645. * @param string $s Header
  2646. * @throws phpmailerException
  2647. * @return string
  2648. */
  2649. public function DKIM_Sign($s) {
  2650. if (!defined('PKCS7_TEXT')) {
  2651. if ($this->exceptions) {
  2652. throw new phpmailerException($this->Lang("signing").' OpenSSL extension missing.');
  2653. }
  2654. return '';
  2655. }
  2656. $privKeyStr = file_get_contents($this->DKIM_private);
  2657. if ($this->DKIM_passphrase != '') {
  2658. $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  2659. } else {
  2660. $privKey = $privKeyStr;
  2661. }
  2662. if (openssl_sign($s, $signature, $privKey)) {
  2663. return base64_encode($signature);
  2664. }
  2665. return '';
  2666. }
  2667. /**
  2668. * Generate DKIM Canonicalization Header
  2669. *
  2670. * @access public
  2671. * @param string $s Header
  2672. * @return string
  2673. */
  2674. public function DKIM_HeaderC($s) {
  2675. $s = preg_replace("/\r\n\s+/", " ", $s);
  2676. $lines = explode("\r\n", $s);
  2677. foreach ($lines as $key => $line) {
  2678. list($heading, $value) = explode(":", $line, 2);
  2679. $heading = strtolower($heading);
  2680. $value = preg_replace("/\s+/", " ", $value) ; // Compress useless spaces
  2681. $lines[$key] = $heading.":".trim($value) ; // Don't forget to remove WSP around the value
  2682. }
  2683. $s = implode("\r\n", $lines);
  2684. return $s;
  2685. }
  2686. /**
  2687. * Generate DKIM Canonicalization Body
  2688. *
  2689. * @access public
  2690. * @param string $body Message Body
  2691. * @return string
  2692. */
  2693. public function DKIM_BodyC($body) {
  2694. if ($body == '') return "\r\n";
  2695. // stabilize line endings
  2696. $body = str_replace("\r\n", "\n", $body);
  2697. $body = str_replace("\n", "\r\n", $body);
  2698. // END stabilize line endings
  2699. while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
  2700. $body = substr($body, 0, strlen($body) - 2);
  2701. }
  2702. return $body;
  2703. }
  2704. /**
  2705. * Create the DKIM header, body, as new header
  2706. *
  2707. * @access public
  2708. * @param string $headers_line Header lines
  2709. * @param string $subject Subject
  2710. * @param string $body Body
  2711. * @return string
  2712. */
  2713. public function DKIM_Add($headers_line, $subject, $body) {
  2714. $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
  2715. $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  2716. $DKIMquery = 'dns/txt'; // Query method
  2717. $DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  2718. $subject_header = "Subject: $subject";
  2719. $headers = explode($this->LE, $headers_line);
  2720. $from_header = '';
  2721. $to_header = '';
  2722. $current = '';
  2723. foreach($headers as $header) {
  2724. if (strpos($header, 'From:') === 0) {
  2725. $from_header = $header;
  2726. $current = 'from_header';
  2727. } elseif (strpos($header, 'To:') === 0) {
  2728. $to_header = $header;
  2729. $current = 'to_header';
  2730. } else {
  2731. if($current && strpos($header, ' =?') === 0){
  2732. $current .= $header;
  2733. } else {
  2734. $current = '';
  2735. }
  2736. }
  2737. }
  2738. $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  2739. $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  2740. $subject = str_replace('|', '=7C', $this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable
  2741. $body = $this->DKIM_BodyC($body);
  2742. $DKIMlen = strlen($body) ; // Length of body
  2743. $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body
  2744. $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";";
  2745. $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n".
  2746. "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n".
  2747. "\th=From:To:Subject;\r\n".
  2748. "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n".
  2749. "\tz=$from\r\n".
  2750. "\t|$to\r\n".
  2751. "\t|$subject;\r\n".
  2752. "\tbh=" . $DKIMb64 . ";\r\n".
  2753. "\tb=";
  2754. $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
  2755. $signed = $this->DKIM_Sign($toSign);
  2756. return $dkimhdrs.$signed."\r\n";
  2757. }
  2758. /**
  2759. * Perform callback
  2760. * @param boolean $isSent
  2761. * @param string $to
  2762. * @param string $cc
  2763. * @param string $bcc
  2764. * @param string $subject
  2765. * @param string $body
  2766. * @param string $from
  2767. */
  2768. protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from = null) {
  2769. if (!empty($this->action_function) && is_callable($this->action_function)) {
  2770. $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
  2771. call_user_func_array($this->action_function, $params);
  2772. }
  2773. }
  2774. }
  2775. /**
  2776. * Exception handler for PHPMailer
  2777. * @package PHPMailer
  2778. */
  2779. class phpmailerException extends Exception {
  2780. /**
  2781. * Prettify error message output
  2782. * @return string
  2783. */
  2784. public function errorMessage() {
  2785. $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  2786. return $errorMsg;
  2787. }
  2788. }