PageRenderTime 116ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 1ms

/libraries/phpmailer/phpmailer.php

https://bitbucket.org/asosso/joomla25
PHP | 2532 lines | 1744 code | 171 blank | 617 comment | 262 complexity | fc19291526ca41be0174feb8f8d04f02 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /*~ class.phpmailer.php
  3. .---------------------------------------------------------------------------.
  4. | Software: PHPMailer - PHP email class |
  5. | Version: 5.2.1 |
  6. | Site: https://code.google.com/a/apache-extras.org/p/phpmailer/ |
  7. | ------------------------------------------------------------------------- |
  8. | Admin: Jim Jagielski (project admininistrator) |
  9. | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
  10. | : Marcus Bointon (coolbru) coolbru@users.sourceforge.net |
  11. | : Jim Jagielski (jimjag) jimjag@gmail.com |
  12. | Founder: Brent R. Matzelle (original founder) |
  13. | Copyright (c) 2010-2012, Jim Jagielski. All Rights Reserved. |
  14. | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. |
  15. | Copyright (c) 2001-2003, Brent R. Matzelle |
  16. | ------------------------------------------------------------------------- |
  17. | License: Distributed under the Lesser General Public License (LGPL) |
  18. | http://www.gnu.org/copyleft/lesser.html |
  19. | This program is distributed in the hope that it will be useful - WITHOUT |
  20. | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
  21. | FITNESS FOR A PARTICULAR PURPOSE. |
  22. '---------------------------------------------------------------------------'
  23. */
  24. /**
  25. * PHPMailer - PHP email transport class
  26. * NOTE: Requires PHP version 5 or later
  27. * @package PHPMailer
  28. * @author Andy Prevost
  29. * @author Marcus Bointon
  30. * @author Jim Jagielski
  31. * @copyright 2010 - 2013 Jim Jagielski
  32. * @copyright 2004 - 2009 Andy Prevost
  33. * @version $Id: class.phpmailer.php 450 2010-06-23 16:46:33Z coolbru $
  34. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  35. */
  36. if (version_compare(PHP_VERSION, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n");
  37. class PHPMailer {
  38. /////////////////////////////////////////////////
  39. // PROPERTIES, PUBLIC
  40. /////////////////////////////////////////////////
  41. /**
  42. * Email priority (1 = High, 3 = Normal, 5 = low).
  43. * @var int
  44. */
  45. public $Priority = 3;
  46. /**
  47. * Sets the CharSet of the message.
  48. * @var string
  49. */
  50. public $CharSet = 'iso-8859-1';
  51. /**
  52. * Sets the Content-type of the message.
  53. * @var string
  54. */
  55. public $ContentType = 'text/plain';
  56. /**
  57. * Sets the Encoding of the message. Options for this are
  58. * "8bit", "7bit", "binary", "base64", and "quoted-printable".
  59. * @var string
  60. */
  61. public $Encoding = '8bit';
  62. /**
  63. * Holds the most recent mailer error message.
  64. * @var string
  65. */
  66. public $ErrorInfo = '';
  67. /**
  68. * Sets the From email address for the message.
  69. * @var string
  70. */
  71. public $From = 'root@localhost';
  72. /**
  73. * Sets the From name of the message.
  74. * @var string
  75. */
  76. public $FromName = 'Root User';
  77. /**
  78. * Sets the Sender email (Return-Path) of the message. If not empty,
  79. * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  80. * @var string
  81. */
  82. public $Sender = '';
  83. /**
  84. * Sets the Subject of the message.
  85. * @var string
  86. */
  87. public $Subject = '';
  88. /**
  89. * Sets the Body of the message. This can be either an HTML or text body.
  90. * If HTML then run IsHTML(true).
  91. * @var string
  92. */
  93. public $Body = '';
  94. /**
  95. * Sets the text-only body of the message. This automatically sets the
  96. * email to multipart/alternative. This body can be read by mail
  97. * clients that do not have HTML email capability such as mutt. Clients
  98. * that can read HTML will view the normal Body.
  99. * @var string
  100. */
  101. public $AltBody = '';
  102. /**
  103. * Stores the complete compiled MIME message body.
  104. * @var string
  105. * @access protected
  106. */
  107. protected $MIMEBody = '';
  108. /**
  109. * Stores the complete compiled MIME message headers.
  110. * @var string
  111. * @access protected
  112. */
  113. protected $MIMEHeader = '';
  114. /**
  115. * Stores the complete sent MIME message (Body and Headers)
  116. * @var string
  117. * @access protected
  118. */
  119. protected $SentMIMEMessage = '';
  120. /**
  121. * Sets word wrapping on the body of the message to a given number of
  122. * characters.
  123. * @var int
  124. */
  125. public $WordWrap = 0;
  126. /**
  127. * Method to send mail: ("mail", "sendmail", or "smtp").
  128. * @var string
  129. */
  130. public $Mailer = 'mail';
  131. /**
  132. * Sets the path of the sendmail program.
  133. * @var string
  134. */
  135. public $Sendmail = '/usr/sbin/sendmail';
  136. /**
  137. * Path to PHPMailer plugins. Useful if the SMTP class
  138. * is in a different directory than the PHP include path.
  139. * @var string
  140. */
  141. public $PluginDir = '';
  142. /**
  143. * Sets the email address that a reading confirmation will be sent.
  144. * @var string
  145. */
  146. public $ConfirmReadingTo = '';
  147. /**
  148. * Sets the hostname to use in Message-Id and Received headers
  149. * and as default HELO string. If empty, the value returned
  150. * by SERVER_NAME is used or 'localhost.localdomain'.
  151. * @var string
  152. */
  153. public $Hostname = '';
  154. /**
  155. * Sets the message ID to be used in the Message-Id header.
  156. * If empty, a unique id will be generated.
  157. * @var string
  158. */
  159. public $MessageID = '';
  160. /////////////////////////////////////////////////
  161. // PROPERTIES FOR SMTP
  162. /////////////////////////////////////////////////
  163. /**
  164. * Sets the SMTP hosts. All hosts must be separated by a
  165. * semicolon. You can also specify a different port
  166. * for each host by using this format: [hostname:port]
  167. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  168. * Hosts will be tried in order.
  169. * @var string
  170. */
  171. public $Host = 'localhost';
  172. /**
  173. * Sets the default SMTP server port.
  174. * @var int
  175. */
  176. public $Port = 25;
  177. /**
  178. * Sets the SMTP HELO of the message (Default is $Hostname).
  179. * @var string
  180. */
  181. public $Helo = '';
  182. /**
  183. * Sets connection prefix.
  184. * Options are "", "ssl" or "tls"
  185. * @var string
  186. */
  187. public $SMTPSecure = '';
  188. /**
  189. * Sets SMTP authentication. Utilizes the Username and Password variables.
  190. * @var bool
  191. */
  192. public $SMTPAuth = false;
  193. /**
  194. * Sets SMTP username.
  195. * @var string
  196. */
  197. public $Username = '';
  198. /**
  199. * Sets SMTP password.
  200. * @var string
  201. */
  202. public $Password = '';
  203. /**
  204. * Sets the SMTP server timeout in seconds.
  205. * This function will not work with the win32 version.
  206. * @var int
  207. */
  208. public $Timeout = 10;
  209. /**
  210. * Sets SMTP class debugging on or off.
  211. * @var bool
  212. */
  213. public $SMTPDebug = false;
  214. /**
  215. * Prevents the SMTP connection from being closed after each mail
  216. * sending. If this is set to true then to close the connection
  217. * requires an explicit call to SmtpClose().
  218. * @var bool
  219. */
  220. public $SMTPKeepAlive = false;
  221. /**
  222. * Provides the ability to have the TO field process individual
  223. * emails, instead of sending to entire TO addresses
  224. * @var bool
  225. */
  226. public $SingleTo = false;
  227. /**
  228. * If SingleTo is true, this provides the array to hold the email addresses
  229. * @var bool
  230. */
  231. public $SingleToArray = array();
  232. /**
  233. * Provides the ability to change the line ending
  234. * @var string
  235. */
  236. public $LE = "\n";
  237. /**
  238. * Used with DKIM DNS Resource Record
  239. * @var string
  240. */
  241. public $DKIM_selector = 'phpmailer';
  242. /**
  243. * Used with DKIM DNS Resource Record
  244. * optional, in format of email address 'you@yourdomain.com'
  245. * @var string
  246. */
  247. public $DKIM_identity = '';
  248. /**
  249. * Used with DKIM DNS Resource Record
  250. * @var string
  251. */
  252. public $DKIM_passphrase = '';
  253. /**
  254. * Used with DKIM DNS Resource Record
  255. * optional, in format of email address 'you@yourdomain.com'
  256. * @var string
  257. */
  258. public $DKIM_domain = '';
  259. /**
  260. * Used with DKIM DNS Resource Record
  261. * optional, in format of email address 'you@yourdomain.com'
  262. * @var string
  263. */
  264. public $DKIM_private = '';
  265. /**
  266. * Callback Action function name
  267. * the function that handles the result of the send email action. Parameters:
  268. * bool $result result of the send action
  269. * string $to email address of the recipient
  270. * string $cc cc email addresses
  271. * string $bcc bcc email addresses
  272. * string $subject the subject
  273. * string $body the email body
  274. * @var string
  275. */
  276. public $action_function = ''; //'callbackAction';
  277. /**
  278. * Sets the PHPMailer Version number
  279. * @var string
  280. */
  281. public $Version = '5.2.1';
  282. /**
  283. * What to use in the X-Mailer header
  284. * @var string
  285. */
  286. public $XMailer = '';
  287. /////////////////////////////////////////////////
  288. // PROPERTIES, PRIVATE AND PROTECTED
  289. /////////////////////////////////////////////////
  290. protected $smtp = NULL;
  291. protected $to = array();
  292. protected $cc = array();
  293. protected $bcc = array();
  294. protected $ReplyTo = array();
  295. protected $all_recipients = array();
  296. protected $attachment = array();
  297. protected $CustomHeader = array();
  298. protected $message_type = '';
  299. protected $boundary = array();
  300. protected $language = array();
  301. protected $error_count = 0;
  302. protected $sign_cert_file = '';
  303. protected $sign_key_file = '';
  304. protected $sign_key_pass = '';
  305. protected $exceptions = false;
  306. /////////////////////////////////////////////////
  307. // CONSTANTS
  308. /////////////////////////////////////////////////
  309. const STOP_MESSAGE = 0; // message only, continue processing
  310. const STOP_CONTINUE = 1; // message?, likely ok to continue processing
  311. const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
  312. /////////////////////////////////////////////////
  313. // METHODS, VARIABLES
  314. /////////////////////////////////////////////////
  315. /**
  316. * Constructor
  317. * @param boolean $exceptions Should we throw external exceptions?
  318. */
  319. public function __construct($exceptions = false) {
  320. $this->exceptions = ($exceptions == true);
  321. }
  322. /**
  323. * Sets message type to HTML.
  324. * @param bool $ishtml
  325. * @return void
  326. */
  327. public function IsHTML($ishtml = true) {
  328. if ($ishtml) {
  329. $this->ContentType = 'text/html';
  330. } else {
  331. $this->ContentType = 'text/plain';
  332. }
  333. }
  334. /**
  335. * Sets Mailer to send message using SMTP.
  336. * @return void
  337. */
  338. public function IsSMTP() {
  339. $this->Mailer = 'smtp';
  340. }
  341. /**
  342. * Sets Mailer to send message using PHP mail() function.
  343. * @return void
  344. */
  345. public function IsMail() {
  346. $this->Mailer = 'mail';
  347. }
  348. /**
  349. * Sets Mailer to send message using the $Sendmail program.
  350. * @return void
  351. */
  352. public function IsSendmail() {
  353. if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
  354. $this->Sendmail = '/var/qmail/bin/sendmail';
  355. }
  356. $this->Mailer = 'sendmail';
  357. }
  358. /**
  359. * Sets Mailer to send message using the qmail MTA.
  360. * @return void
  361. */
  362. public function IsQmail() {
  363. if (stristr(ini_get('sendmail_path'), 'qmail')) {
  364. $this->Sendmail = '/var/qmail/bin/sendmail';
  365. }
  366. $this->Mailer = 'sendmail';
  367. }
  368. /////////////////////////////////////////////////
  369. // METHODS, RECIPIENTS
  370. /////////////////////////////////////////////////
  371. /**
  372. * Adds a "To" address.
  373. * @param string $address
  374. * @param string $name
  375. * @return boolean true on success, false if address already used
  376. */
  377. public function AddAddress($address, $name = '') {
  378. return $this->AddAnAddress('to', $address, $name);
  379. }
  380. /**
  381. * Adds a "Cc" address.
  382. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  383. * @param string $address
  384. * @param string $name
  385. * @return boolean true on success, false if address already used
  386. */
  387. public function AddCC($address, $name = '') {
  388. return $this->AddAnAddress('cc', $address, $name);
  389. }
  390. /**
  391. * Adds a "Bcc" address.
  392. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  393. * @param string $address
  394. * @param string $name
  395. * @return boolean true on success, false if address already used
  396. */
  397. public function AddBCC($address, $name = '') {
  398. return $this->AddAnAddress('bcc', $address, $name);
  399. }
  400. /**
  401. * Adds a "Reply-to" address.
  402. * @param string $address
  403. * @param string $name
  404. * @return boolean
  405. */
  406. public function AddReplyTo($address, $name = '') {
  407. return $this->AddAnAddress('Reply-To', $address, $name);
  408. }
  409. /**
  410. * Adds an address to one of the recipient arrays
  411. * Addresses that have been added already return false, but do not throw exceptions
  412. * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
  413. * @param string $address The email address to send to
  414. * @param string $name
  415. * @return boolean true on success, false if address already used or invalid in some way
  416. * @access protected
  417. */
  418. protected function AddAnAddress($kind, $address, $name = '') {
  419. if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
  420. $this->SetError($this->Lang('Invalid recipient array').': '.$kind);
  421. if ($this->exceptions) {
  422. throw new phpmailerException('Invalid recipient array: ' . $kind);
  423. }
  424. if ($this->SMTPDebug) {
  425. echo $this->Lang('Invalid recipient array').': '.$kind;
  426. }
  427. return false;
  428. }
  429. $address = trim($address);
  430. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  431. if (!self::ValidateAddress($address)) {
  432. $this->SetError($this->Lang('invalid_address').': '. $address);
  433. if ($this->exceptions) {
  434. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  435. }
  436. if ($this->SMTPDebug) {
  437. echo $this->Lang('invalid_address').': '.$address;
  438. }
  439. return false;
  440. }
  441. if ($kind != 'Reply-To') {
  442. if (!isset($this->all_recipients[strtolower($address)])) {
  443. array_push($this->$kind, array($address, $name));
  444. $this->all_recipients[strtolower($address)] = true;
  445. return true;
  446. }
  447. } else {
  448. if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  449. $this->ReplyTo[strtolower($address)] = array($address, $name);
  450. return true;
  451. }
  452. }
  453. return false;
  454. }
  455. /**
  456. * Set the From and FromName properties
  457. * @param string $address
  458. * @param string $name
  459. * @return boolean
  460. */
  461. public function SetFrom($address, $name = '', $auto = 1) {
  462. $address = trim($address);
  463. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  464. if (!self::ValidateAddress($address)) {
  465. $this->SetError($this->Lang('invalid_address').': '. $address);
  466. if ($this->exceptions) {
  467. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  468. }
  469. if ($this->SMTPDebug) {
  470. echo $this->Lang('invalid_address').': '.$address;
  471. }
  472. return false;
  473. }
  474. $this->From = $address;
  475. $this->FromName = $name;
  476. if ($auto) {
  477. if (empty($this->ReplyTo)) {
  478. $this->AddAnAddress('Reply-To', $address, $name);
  479. }
  480. if (empty($this->Sender)) {
  481. $this->Sender = $address;
  482. }
  483. }
  484. return true;
  485. }
  486. /**
  487. * Check that a string looks roughly like an email address should
  488. * Static so it can be used without instantiation
  489. * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator
  490. * Conforms approximately to RFC2822
  491. * @link http://www.hexillion.com/samples/#Regex Original pattern found here
  492. * @param string $address The email address to check
  493. * @return boolean
  494. * @static
  495. * @access public
  496. */
  497. public static function ValidateAddress($address) {
  498. if (function_exists('filter_var')) { //Introduced in PHP 5.2
  499. if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) {
  500. return false;
  501. } else {
  502. return true;
  503. }
  504. } else {
  505. return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address);
  506. }
  507. }
  508. /////////////////////////////////////////////////
  509. // METHODS, MAIL SENDING
  510. /////////////////////////////////////////////////
  511. /**
  512. * Creates message and assigns Mailer. If the message is
  513. * not sent successfully then it returns false. Use the ErrorInfo
  514. * variable to view description of the error.
  515. * @return bool
  516. */
  517. public function Send() {
  518. try {
  519. if(!$this->PreSend()) return false;
  520. return $this->PostSend();
  521. } catch (phpmailerException $e) {
  522. $this->SentMIMEMessage = '';
  523. $this->SetError($e->getMessage());
  524. if ($this->exceptions) {
  525. throw $e;
  526. }
  527. return false;
  528. }
  529. }
  530. protected function PreSend() {
  531. try {
  532. $mailHeader = "";
  533. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  534. throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
  535. }
  536. // Set whether the message is multipart/alternative
  537. if(!empty($this->AltBody)) {
  538. $this->ContentType = 'multipart/alternative';
  539. }
  540. $this->error_count = 0; // reset errors
  541. $this->SetMessageType();
  542. //Refuse to send an empty message
  543. if (empty($this->Body)) {
  544. throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
  545. }
  546. $this->MIMEHeader = $this->CreateHeader();
  547. $this->MIMEBody = $this->CreateBody();
  548. // To capture the complete message when using mail(), create
  549. // an extra header list which CreateHeader() doesn't fold in
  550. if ($this->Mailer == 'mail') {
  551. if (count($this->to) > 0) {
  552. $mailHeader .= $this->AddrAppend("To", $this->to);
  553. } else {
  554. $mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;");
  555. }
  556. $mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject))));
  557. // if(count($this->cc) > 0) {
  558. // $mailHeader .= $this->AddrAppend("Cc", $this->cc);
  559. // }
  560. }
  561. // digitally sign with DKIM if enabled
  562. if ($this->DKIM_domain && $this->DKIM_private) {
  563. $header_dkim = $this->DKIM_Add($this->MIMEHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody);
  564. $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader;
  565. }
  566. $this->SentMIMEMessage = sprintf("%s%s\r\n\r\n%s",$this->MIMEHeader,$mailHeader,$this->MIMEBody);
  567. return true;
  568. } catch (phpmailerException $e) {
  569. $this->SetError($e->getMessage());
  570. if ($this->exceptions) {
  571. throw $e;
  572. }
  573. return false;
  574. }
  575. }
  576. protected function PostSend() {
  577. try {
  578. // Choose the mailer and send through it
  579. switch($this->Mailer) {
  580. case 'sendmail':
  581. return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody);
  582. case 'smtp':
  583. return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);
  584. case 'mail':
  585. return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
  586. default:
  587. return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
  588. }
  589. } catch (phpmailerException $e) {
  590. $this->SetError($e->getMessage());
  591. if ($this->exceptions) {
  592. throw $e;
  593. }
  594. if ($this->SMTPDebug) {
  595. echo $e->getMessage()."\n";
  596. }
  597. return false;
  598. }
  599. }
  600. /**
  601. * Sends mail using the $Sendmail program.
  602. * @param string $header The message headers
  603. * @param string $body The message body
  604. * @access protected
  605. * @return bool
  606. */
  607. protected function SendmailSend($header, $body) {
  608. if ($this->Sender != '') {
  609. $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  610. } else {
  611. $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
  612. }
  613. if ($this->SingleTo === true) {
  614. foreach ($this->SingleToArray as $key => $val) {
  615. if(!@$mail = popen($sendmail, 'w')) {
  616. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  617. }
  618. fputs($mail, "To: " . $val . "\n");
  619. fputs($mail, $header);
  620. fputs($mail, $body);
  621. $result = pclose($mail);
  622. // implement call back function if it exists
  623. $isSent = ($result == 0) ? 1 : 0;
  624. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  625. if($result != 0) {
  626. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  627. }
  628. }
  629. } else {
  630. if(!@$mail = popen($sendmail, 'w')) {
  631. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  632. }
  633. fputs($mail, $header);
  634. fputs($mail, $body);
  635. $result = pclose($mail);
  636. // implement call back function if it exists
  637. $isSent = ($result == 0) ? 1 : 0;
  638. $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body);
  639. if($result != 0) {
  640. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  641. }
  642. }
  643. return true;
  644. }
  645. /**
  646. * Sends mail using the PHP mail() function.
  647. * @param string $header The message headers
  648. * @param string $body The message body
  649. * @access protected
  650. * @return bool
  651. */
  652. protected function MailSend($header, $body) {
  653. $toArr = array();
  654. foreach($this->to as $t) {
  655. $toArr[] = $this->AddrFormat($t);
  656. }
  657. $to = implode(', ', $toArr);
  658. if (empty($this->Sender)) {
  659. $params = "-oi ";
  660. } else {
  661. $params = sprintf("-oi -f %s", $this->Sender);
  662. }
  663. if ($this->Sender != '' and !ini_get('safe_mode')) {
  664. $old_from = ini_get('sendmail_from');
  665. ini_set('sendmail_from', $this->Sender);
  666. if ($this->SingleTo === true && count($toArr) > 1) {
  667. foreach ($toArr as $key => $val) {
  668. $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  669. // implement call back function if it exists
  670. $isSent = ($rt == 1) ? 1 : 0;
  671. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  672. }
  673. } else {
  674. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  675. // implement call back function if it exists
  676. $isSent = ($rt == 1) ? 1 : 0;
  677. $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
  678. }
  679. } else {
  680. if ($this->SingleTo === true && count($toArr) > 1) {
  681. foreach ($toArr as $key => $val) {
  682. $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  683. // implement call back function if it exists
  684. $isSent = ($rt == 1) ? 1 : 0;
  685. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  686. }
  687. } else {
  688. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  689. // implement call back function if it exists
  690. $isSent = ($rt == 1) ? 1 : 0;
  691. $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
  692. }
  693. }
  694. if (isset($old_from)) {
  695. ini_set('sendmail_from', $old_from);
  696. }
  697. if(!$rt) {
  698. throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
  699. }
  700. return true;
  701. }
  702. /**
  703. * Sends mail via SMTP using PhpSMTP
  704. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  705. * @param string $header The message headers
  706. * @param string $body The message body
  707. * @uses SMTP
  708. * @access protected
  709. * @return bool
  710. */
  711. protected function SmtpSend($header, $body) {
  712. require_once $this->PluginDir . 'smtp.php';
  713. $bad_rcpt = array();
  714. if(!$this->SmtpConnect()) {
  715. throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
  716. }
  717. $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
  718. if(!$this->smtp->Mail($smtp_from)) {
  719. throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL);
  720. }
  721. // Attempt to send attach all recipients
  722. foreach($this->to as $to) {
  723. if (!$this->smtp->Recipient($to[0])) {
  724. $bad_rcpt[] = $to[0];
  725. // implement call back function if it exists
  726. $isSent = 0;
  727. $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
  728. } else {
  729. // implement call back function if it exists
  730. $isSent = 1;
  731. $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
  732. }
  733. }
  734. foreach($this->cc as $cc) {
  735. if (!$this->smtp->Recipient($cc[0])) {
  736. $bad_rcpt[] = $cc[0];
  737. // implement call back function if it exists
  738. $isSent = 0;
  739. $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
  740. } else {
  741. // implement call back function if it exists
  742. $isSent = 1;
  743. $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
  744. }
  745. }
  746. foreach($this->bcc as $bcc) {
  747. if (!$this->smtp->Recipient($bcc[0])) {
  748. $bad_rcpt[] = $bcc[0];
  749. // implement call back function if it exists
  750. $isSent = 0;
  751. $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
  752. } else {
  753. // implement call back function if it exists
  754. $isSent = 1;
  755. $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
  756. }
  757. }
  758. if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
  759. $badaddresses = implode(', ', $bad_rcpt);
  760. throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
  761. }
  762. if(!$this->smtp->Data($header . $body)) {
  763. throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
  764. }
  765. if($this->SMTPKeepAlive == true) {
  766. $this->smtp->Reset();
  767. }
  768. return true;
  769. }
  770. /**
  771. * Initiates a connection to an SMTP server.
  772. * Returns false if the operation failed.
  773. * @uses SMTP
  774. * @access public
  775. * @return bool
  776. */
  777. public function SmtpConnect() {
  778. if(is_null($this->smtp)) {
  779. $this->smtp = new SMTP();
  780. }
  781. $this->smtp->do_debug = $this->SMTPDebug;
  782. $hosts = explode(';', $this->Host);
  783. $index = 0;
  784. $connection = $this->smtp->Connected();
  785. // Retry while there is no connection
  786. try {
  787. while($index < count($hosts) && !$connection) {
  788. $hostinfo = array();
  789. if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {
  790. $host = $hostinfo[1];
  791. $port = $hostinfo[2];
  792. } else {
  793. $host = $hosts[$index];
  794. $port = $this->Port;
  795. }
  796. $tls = ($this->SMTPSecure == 'tls');
  797. $ssl = ($this->SMTPSecure == 'ssl');
  798. if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) {
  799. $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());
  800. $this->smtp->Hello($hello);
  801. if ($tls) {
  802. if (!$this->smtp->StartTLS()) {
  803. throw new phpmailerException($this->Lang('tls'));
  804. }
  805. //We must resend HELO after tls negotiation
  806. $this->smtp->Hello($hello);
  807. }
  808. $connection = true;
  809. if ($this->SMTPAuth) {
  810. if (!$this->smtp->Authenticate($this->Username, $this->Password)) {
  811. throw new phpmailerException($this->Lang('authenticate'));
  812. }
  813. }
  814. }
  815. $index++;
  816. if (!$connection) {
  817. throw new phpmailerException($this->Lang('connect_host'));
  818. }
  819. }
  820. } catch (phpmailerException $e) {
  821. $this->smtp->Reset();
  822. if ($this->exceptions) {
  823. throw $e;
  824. }
  825. }
  826. return true;
  827. }
  828. /**
  829. * Closes the active SMTP session if one exists.
  830. * @return void
  831. */
  832. public function SmtpClose() {
  833. if(!is_null($this->smtp)) {
  834. if($this->smtp->Connected()) {
  835. $this->smtp->Quit();
  836. $this->smtp->Close();
  837. }
  838. }
  839. }
  840. /**
  841. * Sets the language for all class error messages.
  842. * Returns false if it cannot load the language file. The default language is English.
  843. * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
  844. * @param string $lang_path Path to the language file directory
  845. * @access public
  846. */
  847. function SetLanguage($langcode = 'en', $lang_path = 'language/') {
  848. //Define full set of translatable strings
  849. $PHPMAILER_LANG = array(
  850. 'provide_address' => 'You must provide at least one recipient email address.',
  851. 'mailer_not_supported' => ' mailer is not supported.',
  852. 'execute' => 'Could not execute: ',
  853. 'instantiate' => 'Could not instantiate mail function.',
  854. 'authenticate' => 'SMTP Error: Could not authenticate.',
  855. 'from_failed' => 'The following From address failed: ',
  856. 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  857. 'data_not_accepted' => 'SMTP Error: Data not accepted.',
  858. 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  859. 'file_access' => 'Could not access file: ',
  860. 'file_open' => 'File Error: Could not open file: ',
  861. 'encoding' => 'Unknown encoding: ',
  862. 'signing' => 'Signing Error: ',
  863. 'smtp_error' => 'SMTP server error: ',
  864. 'empty_message' => 'Message body empty',
  865. 'invalid_address' => 'Invalid address',
  866. 'variable_set' => 'Cannot set or reset variable: '
  867. );
  868. //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
  869. $l = true;
  870. if ($langcode != 'en') { //There is no English translation file
  871. $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
  872. }
  873. $this->language = $PHPMAILER_LANG;
  874. return ($l == true); //Returns false if language not found
  875. }
  876. /**
  877. * Return the current array of language strings
  878. * @return array
  879. */
  880. public function GetTranslations() {
  881. return $this->language;
  882. }
  883. /////////////////////////////////////////////////
  884. // METHODS, MESSAGE CREATION
  885. /////////////////////////////////////////////////
  886. /**
  887. * Creates recipient headers.
  888. * @access public
  889. * @return string
  890. */
  891. public function AddrAppend($type, $addr) {
  892. $addr_str = $type . ': ';
  893. $addresses = array();
  894. foreach ($addr as $a) {
  895. $addresses[] = $this->AddrFormat($a);
  896. }
  897. $addr_str .= implode(', ', $addresses);
  898. $addr_str .= $this->LE;
  899. return $addr_str;
  900. }
  901. /**
  902. * Formats an address correctly.
  903. * @access public
  904. * @return string
  905. */
  906. public function AddrFormat($addr) {
  907. if (empty($addr[1])) {
  908. return $this->SecureHeader($addr[0]);
  909. } else {
  910. return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
  911. }
  912. }
  913. /**
  914. * Wraps message for use with mailers that do not
  915. * automatically perform wrapping and for quoted-printable.
  916. * Original written by philippe.
  917. * @param string $message The message to wrap
  918. * @param integer $length The line length to wrap to
  919. * @param boolean $qp_mode Whether to run in Quoted-Printable mode
  920. * @access public
  921. * @return string
  922. */
  923. public function WrapText($message, $length, $qp_mode = false) {
  924. $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
  925. // If utf-8 encoding is used, we will need to make sure we don't
  926. // split multibyte characters when we wrap
  927. $is_utf8 = (strtolower($this->CharSet) == "utf-8");
  928. $message = $this->FixEOL($message);
  929. if (substr($message, -1) == $this->LE) {
  930. $message = substr($message, 0, -1);
  931. }
  932. $line = explode($this->LE, $message);
  933. $message = '';
  934. for ($i = 0 ;$i < count($line); $i++) {
  935. $line_part = explode(' ', $line[$i]);
  936. $buf = '';
  937. for ($e = 0; $e<count($line_part); $e++) {
  938. $word = $line_part[$e];
  939. if ($qp_mode and (strlen($word) > $length)) {
  940. $space_left = $length - strlen($buf) - 1;
  941. if ($e != 0) {
  942. if ($space_left > 20) {
  943. $len = $space_left;
  944. if ($is_utf8) {
  945. $len = $this->UTF8CharBoundary($word, $len);
  946. } elseif (substr($word, $len - 1, 1) == "=") {
  947. $len--;
  948. } elseif (substr($word, $len - 2, 1) == "=") {
  949. $len -= 2;
  950. }
  951. $part = substr($word, 0, $len);
  952. $word = substr($word, $len);
  953. $buf .= ' ' . $part;
  954. $message .= $buf . sprintf("=%s", $this->LE);
  955. } else {
  956. $message .= $buf . $soft_break;
  957. }
  958. $buf = '';
  959. }
  960. while (strlen($word) > 0) {
  961. $len = $length;
  962. if ($is_utf8) {
  963. $len = $this->UTF8CharBoundary($word, $len);
  964. } elseif (substr($word, $len - 1, 1) == "=") {
  965. $len--;
  966. } elseif (substr($word, $len - 2, 1) == "=") {
  967. $len -= 2;
  968. }
  969. $part = substr($word, 0, $len);
  970. $word = substr($word, $len);
  971. if (strlen($word) > 0) {
  972. $message .= $part . sprintf("=%s", $this->LE);
  973. } else {
  974. $buf = $part;
  975. }
  976. }
  977. } else {
  978. $buf_o = $buf;
  979. $buf .= ($e == 0) ? $word : (' ' . $word);
  980. if (strlen($buf) > $length and $buf_o != '') {
  981. $message .= $buf_o . $soft_break;
  982. $buf = $word;
  983. }
  984. }
  985. }
  986. $message .= $buf . $this->LE;
  987. }
  988. return $message;
  989. }
  990. /**
  991. * Finds last character boundary prior to maxLength in a utf-8
  992. * quoted (printable) encoded string.
  993. * Original written by Colin Brown.
  994. * @access public
  995. * @param string $encodedText utf-8 QP text
  996. * @param int $maxLength find last character boundary prior to this length
  997. * @return int
  998. */
  999. public function UTF8CharBoundary($encodedText, $maxLength) {
  1000. $foundSplitPos = false;
  1001. $lookBack = 3;
  1002. while (!$foundSplitPos) {
  1003. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  1004. $encodedCharPos = strpos($lastChunk, "=");
  1005. if ($encodedCharPos !== false) {
  1006. // Found start of encoded character byte within $lookBack block.
  1007. // Check the encoded byte value (the 2 chars after the '=')
  1008. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  1009. $dec = hexdec($hex);
  1010. if ($dec < 128) { // Single byte character.
  1011. // If the encoded char was found at pos 0, it will fit
  1012. // otherwise reduce maxLength to start of the encoded char
  1013. $maxLength = ($encodedCharPos == 0) ? $maxLength :
  1014. $maxLength - ($lookBack - $encodedCharPos);
  1015. $foundSplitPos = true;
  1016. } elseif ($dec >= 192) { // First byte of a multi byte character
  1017. // Reduce maxLength to split at start of character
  1018. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  1019. $foundSplitPos = true;
  1020. } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
  1021. $lookBack += 3;
  1022. }
  1023. } else {
  1024. // No encoded character found
  1025. $foundSplitPos = true;
  1026. }
  1027. }
  1028. return $maxLength;
  1029. }
  1030. /**
  1031. * Set the body wrapping.
  1032. * @access public
  1033. * @return void
  1034. */
  1035. public function SetWordWrap() {
  1036. if($this->WordWrap < 1) {
  1037. return;
  1038. }
  1039. switch($this->message_type) {
  1040. case 'alt':
  1041. case 'alt_inline':
  1042. case 'alt_attach':
  1043. case 'alt_inline_attach':
  1044. $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
  1045. break;
  1046. default:
  1047. $this->Body = $this->WrapText($this->Body, $this->WordWrap);
  1048. break;
  1049. }
  1050. }
  1051. /**
  1052. * Assembles message header.
  1053. * @access public
  1054. * @return string The assembled header
  1055. */
  1056. public function CreateHeader() {
  1057. $result = '';
  1058. // Set the boundaries
  1059. $uniq_id = md5(uniqid(time()));
  1060. $this->boundary[1] = 'b1_' . $uniq_id;
  1061. $this->boundary[2] = 'b2_' . $uniq_id;
  1062. $this->boundary[3] = 'b3_' . $uniq_id;
  1063. $result .= $this->HeaderLine('Date', self::RFCDate());
  1064. if($this->Sender == '') {
  1065. $result .= $this->HeaderLine('Return-Path', trim($this->From));
  1066. } else {
  1067. $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
  1068. }
  1069. // To be created automatically by mail()
  1070. if($this->Mailer != 'mail') {
  1071. if ($this->SingleTo === true) {
  1072. foreach($this->to as $t) {
  1073. $this->SingleToArray[] = $this->AddrFormat($t);
  1074. }
  1075. } else {
  1076. if(count($this->to) > 0) {
  1077. $result .= $this->AddrAppend('To', $this->to);
  1078. } elseif (count($this->cc) == 0) {
  1079. $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
  1080. }
  1081. }
  1082. }
  1083. $from = array();
  1084. $from[0][0] = trim($this->From);
  1085. $from[0][1] = $this->FromName;
  1086. $result .= $this->AddrAppend('From', $from);
  1087. // sendmail and mail() extract Cc from the header before sending
  1088. if(count($this->cc) > 0) {
  1089. $result .= $this->AddrAppend('Cc', $this->cc);
  1090. }
  1091. // sendmail and mail() extract Bcc from the header before sending
  1092. if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
  1093. $result .= $this->AddrAppend('Bcc', $this->bcc);
  1094. }
  1095. if(count($this->ReplyTo) > 0) {
  1096. $result .= $this->AddrAppend('Reply-To', $this->ReplyTo);
  1097. }
  1098. // mail() sets the subject itself
  1099. if($this->Mailer != 'mail') {
  1100. $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
  1101. }
  1102. if($this->MessageID != '') {
  1103. $result .= $this->HeaderLine('Message-ID', $this->MessageID);
  1104. } else {
  1105. $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
  1106. }
  1107. $result .= $this->HeaderLine('X-Priority', $this->Priority);
  1108. if($this->XMailer) {
  1109. $result .= $this->HeaderLine('X-Mailer', $this->XMailer);
  1110. } else {
  1111. $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (http://code.google.com/a/apache-extras.org/p/phpmailer/)');
  1112. }
  1113. if($this->ConfirmReadingTo != '') {
  1114. $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
  1115. }
  1116. // Add custom headers
  1117. for($index = 0; $index < count($this->CustomHeader); $index++) {
  1118. $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
  1119. }
  1120. if (!$this->sign_key_file) {
  1121. $result .= $this->HeaderLine('MIME-Version', '1.0');
  1122. $result .= $this->GetMailMIME();
  1123. }
  1124. return $result;
  1125. }
  1126. /**
  1127. * Returns the message MIME.
  1128. * @access public
  1129. * @return string
  1130. */
  1131. public function GetMailMIME() {
  1132. $result = '';
  1133. switch($this->message_type) {
  1134. case 'plain':
  1135. $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
  1136. $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset="'.$this->CharSet.'"');
  1137. break;
  1138. case 'inline':
  1139. $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1140. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  1141. break;
  1142. case 'attach':
  1143. case 'inline_attach':
  1144. case 'alt_attach':
  1145. case 'alt_inline_attach':
  1146. $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
  1147. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  1148. break;
  1149. case 'alt':
  1150. case 'alt_inline':
  1151. $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1152. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  1153. break;
  1154. }
  1155. if($this->Mailer != 'mail') {
  1156. $result .= $this->LE.$this->LE;
  1157. }
  1158. return $result;
  1159. }
  1160. /**
  1161. * Returns the MIME message (headers and body). Only really valid post PreSend().
  1162. * @access public
  1163. * @return string
  1164. */
  1165. public function GetSentMIMEMessage() {
  1166. return $this->SentMIMEMessage;
  1167. }
  1168. /**
  1169. * Assembles the message body. Returns an empty string on failure.
  1170. * @access public
  1171. * @return string The assembled message body
  1172. */
  1173. public function CreateBody() {
  1174. $body = '';
  1175. if ($this->sign_key_file) {
  1176. $body .= $this->GetMailMIME();
  1177. }
  1178. $this->SetWordWrap();
  1179. switch($this->message_type) {
  1180. case 'plain':
  1181. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1182. break;
  1183. case 'inline':
  1184. $body .= $this->GetBoundary($this->boundary[1], '', '', '');
  1185. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1186. $body .= $this->LE.$this->LE;
  1187. $body .= $this->AttachAll("inline", $this->boundary[1]);
  1188. break;
  1189. case 'attach':
  1190. $body .= $this->GetBoundary($this->boundary[1], '', '', '');
  1191. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1192. $body .= $this->LE.$this->LE;
  1193. $body .= $this->AttachAll("attachment", $this->boundary[1]);
  1194. break;
  1195. case 'inline_attach':
  1196. $body .= $this->TextLine("--" . $this->boundary[1]);
  1197. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1198. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
  1199. $body .= $this->LE;
  1200. $body .= $this->GetBoundary($this->boundary[2], '', '', '');
  1201. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1202. $body .= $this->LE.$this->LE;
  1203. $body .= $this->AttachAll("inline", $this->boundary[2]);
  1204. $body .= $this->LE;
  1205. $body .= $this->AttachAll("attachment", $this->boundary[1]);
  1206. break;
  1207. case 'alt':
  1208. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  1209. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1210. $body .= $this->LE.$this->LE;
  1211. $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
  1212. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1213. $body .= $this->LE.$this->LE;
  1214. $body .= $this->EndBoundary($this->boundary[1]);
  1215. break;
  1216. case 'alt_inline':
  1217. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  1218. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1219. $body .= $this->LE.$this->LE;
  1220. $body .= $this->TextLine("--" . $this->boundary[1]);
  1221. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1222. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
  1223. $body .= $this->LE;
  1224. $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
  1225. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1226. $body .= $this->LE.$this->LE;
  1227. $body .= $this->AttachAll("inline", $this->boundary[2]);
  1228. $body .= $this->LE;
  1229. $body .= $this->EndBoundary($this->boundary[1]);
  1230. break;
  1231. case 'alt_attach':
  1232. $body .= $this->TextLine("--" . $this->boundary[1]);
  1233. $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1234. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
  1235. $body .= $this->LE;
  1236. $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
  1237. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1238. $body .= $this->LE.$this->LE;
  1239. $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
  1240. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1241. $body .= $this->LE.$this->LE;
  1242. $body .= $this->EndBoundary($this->boundary[2]);
  1243. $body .= $this->LE;
  1244. $body .= $this->AttachAll("attachment", $this->boundary[1]);
  1245. break;
  1246. case 'alt_inline_attach':
  1247. $body .= $this->TextLine("--" . $this->boundary[1]);
  1248. $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  1249. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
  1250. $body .= $this->LE;
  1251. $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
  1252. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  1253. $body .= $this->LE.$this->LE;
  1254. $body .= $this->TextLine("--" . $this->boundary[2]);
  1255. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  1256. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3] . '"');
  1257. $body .= $this->LE;
  1258. $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', '');
  1259. $body .= $this->EncodeString($this->Body, $this->Encoding);
  1260. $body .= $this->LE.$this->LE;
  1261. $body .= $this->AttachAll("inline", $this->boundary[3]);
  1262. $body .= $this->LE;
  1263. $body .= $this->EndBoundary($this->boundary[2]);
  1264. $body .= $this->LE;
  1265. $body .= $this->AttachAll("attachment", $this->boundary[1]);
  1266. break;
  1267. }
  1268. if ($this->IsError()) {
  1269. $body = '';
  1270. } elseif ($this->sign_key_file) {
  1271. try {
  1272. $file = tempnam('', 'mail');
  1273. file_put_contents($file, $body); //TODO check this worked
  1274. $signed = tempnam("", "signed");
  1275. if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) {
  1276. @unlink($file);
  1277. $body = file_get_contents($signed);
  1278. @unlink($signed);
  1279. } else {
  1280. @unlink($file);
  1281. @unlink($signed);
  1282. throw new phpmailerException($this->Lang("signing").openssl_error_string());
  1283. }
  1284. } catch (phpmailerException $e) {
  1285. $body = '';
  1286. if ($this->exceptions) {
  1287. throw $e;
  1288. }
  1289. }
  1290. }
  1291. return $body;
  1292. }
  1293. /**
  1294. * Returns the start of a message boundary.
  1295. * @access protected
  1296. * @return string
  1297. */
  1298. protected function GetBoundary($boundary, $charSet, $contentType, $encoding) {
  1299. $result = '';
  1300. if($charSet == '') {
  1301. $charSet = $this->CharSet;
  1302. }
  1303. if($contentType == '') {
  1304. $contentType = $this->ContentType;
  1305. }
  1306. if($encoding == '') {
  1307. $encoding = $this->Encoding;
  1308. }
  1309. $result .= $this->TextLine('--' . $boundary);
  1310. $result .= sprintf("Content-Type: %s; charset=\"%s\"", $contentType, $charSet);
  1311. $result .= $this->LE;
  1312. $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
  1313. $result .= $this->LE;
  1314. return $result;
  1315. }
  1316. /**
  1317. * Returns the end of a message boundary.
  1318. * @access protected
  1319. * @return string
  1320. */
  1321. protected function EndBoundary($boundary) {
  1322. return $this->LE . '--' . $boundary . '--' . $this->LE;
  1323. }
  1324. /**
  1325. * Sets the message type.
  1326. * @access protected
  1327. * @return void
  1328. */
  1329. protected function SetMessageType() {
  1330. $this->message_type = array();
  1331. if($this->AlternativeExists()) $this->message_type[] = "alt";
  1332. if($this->InlineImageExists()) $this->message_type[] = "inline";
  1333. if($this->AttachmentExists()) $this->message_type[] = "attach";
  1334. $this->message_type = implode("_", $this->message_type);
  1335. if($this->message_type == "") $this->message_type = "plain";
  1336. }
  1337. /**
  1338. * Returns a formatted header line.
  1339. * @access public
  1340. * @return string
  1341. */
  1342. public function HeaderLine($name, $value) {
  1343. return $name . ': ' . $value . $this->LE;
  1344. }
  1345. /**
  1346. * Returns a formatted mail line.
  1347. * @access public
  1348. * @return string
  1349. */
  1350. public function TextLine($value) {
  1351. return $value . $this->LE;
  1352. }
  1353. /////////////////////////////////////////////////
  1354. // CLASS METHODS, ATTACHMENTS
  1355. /////////////////////////////////////////////////
  1356. /**
  1357. * Adds an attachment from a path on the filesystem.
  1358. * Returns false if the file could not be found
  1359. * or accessed.
  1360. * @param string $path Path to the attachment.
  1361. * @param string $name Overrides the attachment name.
  1362. * @param string $encoding File encoding (see $Encoding).
  1363. * @param string $type File extension (MIME) type.
  1364. * @return bool
  1365. */
  1366. public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
  1367. try {
  1368. if ( !@is_file($path) ) {
  1369. throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
  1370. }
  1371. $filename = basename($path);
  1372. if ( $name == '' ) {
  1373. $name = $filename;
  1374. }
  1375. $this->attachment[] = array(
  1376. 0 => $path,
  1377. 1 => $filename,
  1378. 2 => $name,
  1379. 3 => $encoding,
  1380. 4 => $type,
  1381. 5 => false, // isStringAttachment
  1382. 6 => 'attachment',
  1383. 7 => 0
  1384. );
  1385. } catch (phpmailerException $e) {
  1386. $this->SetError($e->getMessage());
  1387. if ($this->exceptions) {
  1388. throw $e;
  1389. }
  1390. if ($this->SMTPDebug) {
  1391. echo $e->getMessage()."\n";
  1392. }
  1393. if ( $e->getCode() == self::STOP_CRITICAL ) {
  1394. return false;
  1395. }
  1396. }
  1397. return true;
  1398. }
  1399. /**
  1400. * Return the current array of attachments
  1401. * @return array
  1402. */
  1403. public function GetAttachments() {
  1404. return $this->attachment;
  1405. }
  1406. /**
  1407. * Attaches all fs, string, and binary attachments to the message.
  1408. * Returns an empty string on failure.
  1409. * @access protected
  1410. * @return string
  1411. */
  1412. protected function AttachAll($disposition_type, $boundary) {
  1413. // Return text of body
  1414. $mime = array();
  1415. $cidUniq = array();
  1416. $incl = array();
  1417. // Add all attachments
  1418. foreach ($this->attachment as $attachment) {
  1419. // CHECK IF IT IS A VALID DISPOSITION_FILTER
  1420. if($attachment[6] == $disposition_type) {
  1421. // Check for string attachment
  1422. $bString = $attachment[5];
  1423. if ($bString) {
  1424. $string = $attachment[0];
  1425. } else {
  1426. $path = $attachment[0];
  1427. }
  1428. $inclhash = md5(serialize($attachment));
  1429. if (in_array($inclhash, $incl)) { continue; }
  1430. $incl[] = $inclhash;
  1431. $filename = $attachment[1];
  1432. $name = $attachment[2];
  1433. $encoding = $attachment[3];
  1434. $type = $attachment[4];
  1435. $disposition = $attachment[6];
  1436. $cid = $attachment[7];
  1437. if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
  1438. $cidUniq[$cid] = true;
  1439. $mime[] = sprintf("--%s%s", $boundary, $this->LE);
  1440. $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
  1441. $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
  1442. if($disposition == 'inline') {
  1443. $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
  1444. }
  1445. $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
  1446. // Encode as string attachment
  1447. if($bString) {
  1448. $mime[] = $this->EncodeString($string, $encoding);
  1449. if($this->IsError()) {
  1450. return '';
  1451. }
  1452. $mime[] = $this->LE.$this->LE;
  1453. } else {
  1454. $mime[] = $this->EncodeFile($path, $encoding);
  1455. if($this->IsError()) {
  1456. return '';
  1457. }
  1458. $mime[] = $this->LE.$this->LE;
  1459. }
  1460. }
  1461. }
  1462. $mime[] = sprintf("--%s--%s", $boundary, $this->LE);
  1463. return implode("", $mime);
  1464. }
  1465. /**
  1466. * Encodes attachment in requested format.
  1467. * Returns an empty string on failure.
  1468. * @param string $path The full path to the file
  1469. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1470. * @see EncodeFile()
  1471. * @access protected
  1472. * @return string
  1473. */
  1474. protected function EncodeFile($path, $encoding = 'base64') {
  1475. try {
  1476. if (!is_readable($path)) {
  1477. throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
  1478. }
  1479. if (function_exists('get_magic_quotes')) {
  1480. function get_magic_quotes() {
  1481. return false;
  1482. }
  1483. }
  1484. $magic_quotes = get_magic_quotes_runtime();
  1485. if ($magic_quotes) {
  1486. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  1487. set_magic_quotes_runtime(0);
  1488. } else {
  1489. ini_set('magic_quotes_runtime', 0);
  1490. }
  1491. }
  1492. $file_buffer = file_get_contents($path);
  1493. $file_buffer = $this->EncodeString($file_buffer, $encoding);
  1494. if ($magic_quotes) {
  1495. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  1496. set_magic_quotes_runtime($magic_quotes);
  1497. } else {
  1498. ini_set('magic_quotes_runtime', $magic_quotes);
  1499. }
  1500. }
  1501. return $file_buffer;
  1502. } catch (Exception $e) {
  1503. $this->SetError($e->getMessage());
  1504. return '';
  1505. }
  1506. }
  1507. /**
  1508. * Encodes string to requested format.
  1509. * Returns an empty string on failure.
  1510. * @param string $str The text to encode
  1511. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1512. * @access public
  1513. * @return string
  1514. */
  1515. public function EncodeString($str, $encoding = 'base64') {
  1516. $encoded = '';
  1517. switch(strtolower($encoding)) {
  1518. case 'base64':
  1519. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  1520. break;
  1521. case '7bit':
  1522. case '8bit':
  1523. $encoded = $this->FixEOL($str);
  1524. //Make sure it ends with a line break
  1525. if (substr($encoded, -(strlen($this->LE))) != $this->LE)
  1526. $encoded .= $this->LE;
  1527. break;
  1528. case 'binary':
  1529. $encoded = $str;
  1530. break;
  1531. case 'quoted-printable':
  1532. $encoded = $this->EncodeQP($str);
  1533. break;
  1534. default:
  1535. $this->SetError($this->Lang('encoding') . $encoding);
  1536. break;
  1537. }
  1538. return $encoded;
  1539. }
  1540. /**
  1541. * Encode a header string to best (shortest) of Q, B, quoted or none.
  1542. * @access public
  1543. * @return string
  1544. */
  1545. public function EncodeHeader($str, $position = 'text') {
  1546. $x = 0;
  1547. switch (strtolower($position)) {
  1548. case 'phrase':
  1549. if (!preg_match('/[\200-\377]/', $str)) {
  1550. // Can't use addslashes as we don't know what value has magic_quotes_sybase
  1551. $encoded = addcslashes($str, "\0..\37\177\\\"");
  1552. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  1553. return ($encoded);
  1554. } else {
  1555. return ("\"$encoded\"");
  1556. }
  1557. }
  1558. $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  1559. break;
  1560. case 'comment':
  1561. $x = preg_match_all('/[()"]/', $str, $matches);
  1562. // Fall-through
  1563. case 'text':
  1564. default:
  1565. $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  1566. break;
  1567. }
  1568. if ($x == 0) {
  1569. return ($str);
  1570. }
  1571. $maxlen = 75 - 7 - strlen($this->CharSet);
  1572. // Try to select the encoding which should produce the shortest output
  1573. if (strlen($str)/3 < $x) {
  1574. $encoding = 'B';
  1575. if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
  1576. // Use a custom function which correctly encodes and wraps long
  1577. // multibyte strings without breaking lines within a character
  1578. $encoded = $this->Base64EncodeWrapMB($str);
  1579. } else {
  1580. $encoded = base64_encode($str);
  1581. $maxlen -= $maxlen % 4;
  1582. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  1583. }
  1584. } else {
  1585. $encoding = 'Q';
  1586. $encoded = $this->EncodeQ($str, $position);
  1587. $encoded = $this->WrapText($encoded, $maxlen, true);
  1588. $encoded = str_replace('='.$this->LE, "\n", trim($encoded));
  1589. }
  1590. $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
  1591. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  1592. return $encoded;
  1593. }
  1594. /**
  1595. * Checks if a string contains multibyte characters.
  1596. * @access public
  1597. * @param string $str multi-byte text to wrap encode
  1598. * @return bool
  1599. */
  1600. public function HasMultiBytes($str) {
  1601. if (function_exists('mb_strlen')) {
  1602. return (strlen($str) > mb_strlen($str, $this->CharSet));
  1603. } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  1604. return false;
  1605. }
  1606. }
  1607. /**
  1608. * Correctly encodes and wraps long multibyte strings for mail headers
  1609. * without breaking lines within a character.
  1610. * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
  1611. * @access public
  1612. * @param string $str multi-byte text to wrap encode
  1613. * @return string
  1614. */
  1615. public function Base64EncodeWrapMB($str) {
  1616. $start = "=?".$this->CharSet."?B?";
  1617. $end = "?=";
  1618. $encoded = "";
  1619. $mb_length = mb_strlen($str, $this->CharSet);
  1620. // Each line must have length <= 75, including $start and $end
  1621. $length = 75 - strlen($start) - strlen($end);
  1622. // Average multi-byte ratio
  1623. $ratio = $mb_length / strlen($str);
  1624. // Base64 has a 4:3 ratio
  1625. $offset = $avgLength = floor($length * $ratio * .75);
  1626. for ($i = 0; $i < $mb_length; $i += $offset) {
  1627. $lookBack = 0;
  1628. do {
  1629. $offset = $avgLength - $lookBack;
  1630. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  1631. $chunk = base64_encode($chunk);
  1632. $lookBack++;
  1633. }
  1634. while (strlen($chunk) > $length);
  1635. $encoded .= $chunk . $this->LE;
  1636. }
  1637. // Chomp the last linefeed
  1638. $encoded = substr($encoded, 0, -strlen($this->LE));
  1639. return $encoded;
  1640. }
  1641. /**
  1642. * Encode string to quoted-printable.
  1643. * Only uses standard PHP, slow, but will always work
  1644. * @access public
  1645. * @param string $string the text to encode
  1646. * @param integer $line_max Number of chars allowed on a line before wrapping
  1647. * @return string
  1648. */
  1649. public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) {
  1650. $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
  1651. $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
  1652. $eol = "\r\n";
  1653. $escape = '=';
  1654. $output = '';
  1655. while( list(, $line) = each($lines) ) {
  1656. $linlen = strlen($line);
  1657. $newline = '';
  1658. for($i = 0; $i < $linlen; $i++) {
  1659. $c = substr( $line, $i, 1 );
  1660. $dec = ord( $c );
  1661. if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E
  1662. $c = '=2E';
  1663. }
  1664. if ( $dec == 32 ) {
  1665. if ( $i == ( $linlen - 1 ) ) { // convert space at eol only
  1666. $c = '=20';
  1667. } else if ( $space_conv ) {
  1668. $c = '=20';
  1669. }
  1670. } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
  1671. $h2 = floor($dec/16);
  1672. $h1 = floor($dec%16);
  1673. $c = $escape.$hex[$h2].$hex[$h1];
  1674. }
  1675. if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
  1676. $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
  1677. $newline = '';
  1678. // check if newline first character will be point or not
  1679. if ( $dec == 46 ) {
  1680. $c = '=2E';
  1681. }
  1682. }
  1683. $newline .= $c;
  1684. } // end of for
  1685. $output .= $newline.$eol;
  1686. } // end of while
  1687. return $output;
  1688. }
  1689. /**
  1690. * Encode string to RFC2045 (6.7) quoted-printable format
  1691. * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version
  1692. * Also results in same content as you started with after decoding
  1693. * @see EncodeQPphp()
  1694. * @access public
  1695. * @param string $string the text to encode
  1696. * @param integer $line_max Number of chars allowed on a line before wrapping
  1697. * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function
  1698. * @return string
  1699. * @author Marcus Bointon
  1700. */
  1701. public function EncodeQP($string, $line_max = 76, $space_conv = false) {
  1702. if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
  1703. return quoted_printable_encode($string);
  1704. }
  1705. $filters = stream_get_filters();
  1706. if (!in_array('convert.*', $filters)) { //Got convert stream filter?
  1707. return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation
  1708. }
  1709. $fp = fopen('php://temp/', 'r+');
  1710. $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks
  1711. $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE);
  1712. $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);
  1713. fputs($fp, $string);
  1714. rewind($fp);
  1715. $out = stream_get_contents($fp);
  1716. stream_filter_remove($s);
  1717. $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange
  1718. fclose($fp);
  1719. return $out;
  1720. }
  1721. /**
  1722. * Encode string to q encoding.
  1723. * @link http://tools.ietf.org/html/rfc2047
  1724. * @param string $str the text to encode
  1725. * @param string $position Where the text is going to be used, see the RFC for what that means
  1726. * @access public
  1727. * @return string
  1728. */
  1729. public function EncodeQ($str, $position = 'text') {
  1730. // There should not be any EOL in the string
  1731. $encoded = preg_replace('/[\r\n]*/', '', $str);
  1732. switch (strtolower($position)) {
  1733. case 'phrase':
  1734. $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
  1735. break;
  1736. case 'comment':
  1737. $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
  1738. case 'text':
  1739. default:
  1740. // Replace every high ascii, control =, ? and _ characters
  1741. //TODO using /e (equivalent to eval()) is probably not a good idea
  1742. $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
  1743. "'='.sprintf('%02X', ord(stripslashes('\\1')))", $encoded);
  1744. break;
  1745. }
  1746. // Replace every spaces to _ (more readable than =20)
  1747. $encoded = str_replace(' ', '_', $encoded);
  1748. return $encoded;
  1749. }
  1750. /**
  1751. * Adds a string or binary attachment (non-filesystem) to the list.
  1752. * This method can be used to attach ascii or binary data,
  1753. * such as a BLOB record from a database.
  1754. * @param string $string String attachment data.
  1755. * @param string $filename Name of the attachment.
  1756. * @param string $encoding File encoding (see $Encoding).
  1757. * @param string $type File extension (MIME) type.
  1758. * @return void
  1759. */
  1760. public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
  1761. // Append to $attachment array
  1762. $this->attachment[] = array(
  1763. 0 => $string,
  1764. 1 => $filename,
  1765. 2 => basename($filename),
  1766. 3 => $encoding,
  1767. 4 => $type,
  1768. 5 => true, // isStringAttachment
  1769. 6 => 'attachment',
  1770. 7 => 0
  1771. );
  1772. }
  1773. /**
  1774. * Adds an embedded attachment. This can include images, sounds, and
  1775. * just about any other document. Make sure to set the $type to an
  1776. * image type. For JPEG images use "image/jpeg" and for GIF images
  1777. * use "image/gif".
  1778. * @param string $path Path to the attachment.
  1779. * @param string $cid Content ID of the attachment. Use this to identify
  1780. * the Id for accessing the image in an HTML form.
  1781. * @param string $name Overrides the attachment name.
  1782. * @param string $encoding File encoding (see $Encoding).
  1783. * @param string $type File extension (MIME) type.
  1784. * @return bool
  1785. */
  1786. public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
  1787. if ( !@is_file($path) ) {
  1788. $this->SetError($this->Lang('file_access') . $path);
  1789. return false;
  1790. }
  1791. $filename = basename($path);
  1792. if ( $name == '' ) {
  1793. $name = $filename;
  1794. }
  1795. // Append to $attachment array
  1796. $this->attachment[] = array(
  1797. 0 => $path,
  1798. 1 => $filename,
  1799. 2 => $name,
  1800. 3 => $encoding,
  1801. 4 => $type,
  1802. 5 => false, // isStringAttachment
  1803. 6 => 'inline',
  1804. 7 => $cid
  1805. );
  1806. return true;
  1807. }
  1808. public function AddStringEmbeddedImage($string, $cid, $filename = '', $encoding = 'base64', $type = 'application/octet-stream') {
  1809. // Append to $attachment array
  1810. $this->attachment[] = array(
  1811. 0 => $string,
  1812. 1 => $filename,
  1813. 2 => basename($filename),
  1814. 3 => $encoding,
  1815. 4 => $type,
  1816. 5 => true, // isStringAttachment
  1817. 6 => 'inline',
  1818. 7 => $cid
  1819. );
  1820. }
  1821. /**
  1822. * Returns true if an inline attachment is present.
  1823. * @access public
  1824. * @return bool
  1825. */
  1826. public function InlineImageExists() {
  1827. foreach($this->attachment as $attachment) {
  1828. if ($attachment[6] == 'inline') {
  1829. return true;
  1830. }
  1831. }
  1832. return false;
  1833. }
  1834. public function AttachmentExists() {
  1835. foreach($this->attachment as $attachment) {
  1836. if ($attachment[6] == 'attachment') {
  1837. return true;
  1838. }
  1839. }
  1840. return false;
  1841. }
  1842. public function AlternativeExists() {
  1843. return strlen($this->AltBody)>0;
  1844. }
  1845. /////////////////////////////////////////////////
  1846. // CLASS METHODS, MESSAGE RESET
  1847. /////////////////////////////////////////////////
  1848. /**
  1849. * Clears all recipients assigned in the TO array. Returns void.
  1850. * @return void
  1851. */
  1852. public function ClearAddresses() {
  1853. foreach($this->to as $to) {
  1854. unset($this->all_recipients[strtolower($to[0])]);
  1855. }
  1856. $this->to = array();
  1857. }
  1858. /**
  1859. * Clears all recipients assigned in the CC array. Returns void.
  1860. * @return void
  1861. */
  1862. public function ClearCCs() {
  1863. foreach($this->cc as $cc) {
  1864. unset($this->all_recipients[strtolower($cc[0])]);
  1865. }
  1866. $this->cc = array();
  1867. }
  1868. /**
  1869. * Clears all recipients assigned in the BCC array. Returns void.
  1870. * @return void
  1871. */
  1872. public function ClearBCCs() {
  1873. foreach($this->bcc as $bcc) {
  1874. unset($this->all_recipients[strtolower($bcc[0])]);
  1875. }
  1876. $this->bcc = array();
  1877. }
  1878. /**
  1879. * Clears all recipients assigned in the ReplyTo array. Returns void.
  1880. * @return void
  1881. */
  1882. public function ClearReplyTos() {
  1883. $this->ReplyTo = array();
  1884. }
  1885. /**
  1886. * Clears all recipients assigned in the TO, CC and BCC
  1887. * array. Returns void.
  1888. * @return void
  1889. */
  1890. public function ClearAllRecipients() {
  1891. $this->to = array();
  1892. $this->cc = array();
  1893. $this->bcc = array();
  1894. $this->all_recipients = array();
  1895. }
  1896. /**
  1897. * Clears all previously set filesystem, string, and binary
  1898. * attachments. Returns void.
  1899. * @return void
  1900. */
  1901. public function ClearAttachments() {
  1902. $this->attachment = array();
  1903. }
  1904. /**
  1905. * Clears all custom headers. Returns void.
  1906. * @return void
  1907. */
  1908. public function ClearCustomHeaders() {
  1909. $this->CustomHeader = array();
  1910. }
  1911. /////////////////////////////////////////////////
  1912. // CLASS METHODS, MISCELLANEOUS
  1913. /////////////////////////////////////////////////
  1914. /**
  1915. * Adds the error message to the error container.
  1916. * @access protected
  1917. * @return void
  1918. */
  1919. protected function SetError($msg) {
  1920. $this->error_count++;
  1921. if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  1922. $lasterror = $this->smtp->getError();
  1923. if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
  1924. $msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
  1925. }
  1926. }
  1927. $this->ErrorInfo = $msg;
  1928. }
  1929. /**
  1930. * Returns the proper RFC 822 formatted date.
  1931. * @access public
  1932. * @return string
  1933. * @static
  1934. */
  1935. public static function RFCDate() {
  1936. $tz = date('Z');
  1937. $tzs = ($tz < 0) ? '-' : '+';
  1938. $tz = abs($tz);
  1939. $tz = (int)($tz/3600)*100 + ($tz%3600)/60;
  1940. $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
  1941. return $result;
  1942. }
  1943. /**
  1944. * Returns the server hostname or 'localhost.localdomain' if unknown.
  1945. * @access protected
  1946. * @return string
  1947. */
  1948. protected function ServerHostname() {
  1949. if (!empty($this->Hostname)) {
  1950. $result = $this->Hostname;
  1951. } elseif (isset($_SERVER['SERVER_NAME'])) {
  1952. $result = $_SERVER['SERVER_NAME'];
  1953. } else {
  1954. $result = 'localhost.localdomain';
  1955. }
  1956. return $result;
  1957. }
  1958. /**
  1959. * Returns a message in the appropriate language.
  1960. * @access protected
  1961. * @return string
  1962. */
  1963. protected function Lang($key) {
  1964. if(count($this->language) < 1) {
  1965. $this->SetLanguage('en'); // set the default language
  1966. }
  1967. if(isset($this->language[$key])) {
  1968. return $this->language[$key];
  1969. } else {
  1970. return 'Language string failed to load: ' . $key;
  1971. }
  1972. }
  1973. /**
  1974. * Returns true if an error occurred.
  1975. * @access public
  1976. * @return bool
  1977. */
  1978. public function IsError() {
  1979. return ($this->error_count > 0);
  1980. }
  1981. /**
  1982. * Changes every end of line from CR or LF to CRLF.
  1983. * @access public
  1984. * @return string
  1985. */
  1986. public function FixEOL($str) {
  1987. $str = str_replace("\r\n", "\n", $str);
  1988. $str = str_replace("\r", "\n", $str);
  1989. $str = str_replace("\n", $this->LE, $str);
  1990. return $str;
  1991. }
  1992. /**
  1993. * Adds a custom header.
  1994. * @access public
  1995. * @return void
  1996. */
  1997. public function AddCustomHeader($custom_header) {
  1998. $this->CustomHeader[] = explode(':', $custom_header, 2);
  1999. }
  2000. /**
  2001. * Evaluates the message and returns modifications for inline images and backgrounds
  2002. * @access public
  2003. * @return $message
  2004. */
  2005. public function MsgHTML($message, $basedir = '') {
  2006. preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images);
  2007. if(isset($images[2])) {
  2008. foreach($images[2] as $i => $url) {
  2009. // do not change urls for absolute images (thanks to corvuscorax)
  2010. if (!preg_match('#^[A-z]+://#', $url)) {
  2011. $filename = basename($url);
  2012. $directory = dirname($url);
  2013. ($directory == '.') ? $directory='': '';
  2014. $cid = 'cid:' . md5($filename);
  2015. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  2016. $mimeType = self::_mime_types($ext);
  2017. if ( strlen($basedir) > 1 && substr($basedir, -1) != '/') { $basedir .= '/'; }
  2018. if ( strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; }
  2019. if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64', $mimeType) ) {
  2020. $message = preg_replace("/".$images[1][$i]."=[\"']".preg_quote($url, '/')."[\"']/Ui", $images[1][$i]."=\"".$cid."\"", $message);
  2021. }
  2022. }
  2023. }
  2024. }
  2025. $this->IsHTML(true);
  2026. $this->Body = $message;
  2027. if (empty($this->AltBody)) {
  2028. $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $message)));
  2029. if (!empty($textMsg)) {
  2030. $this->AltBody = html_entity_decode($textMsg, ENT_QUOTES, $this->CharSet);
  2031. }
  2032. }
  2033. if (empty($this->AltBody)) {
  2034. $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
  2035. }
  2036. return $message;
  2037. }
  2038. /**
  2039. * Gets the MIME type of the embedded or inline image
  2040. * @param string File extension
  2041. * @access public
  2042. * @return string MIME type of ext
  2043. * @static
  2044. */
  2045. public static function _mime_types($ext = '') {
  2046. $mimes = array(
  2047. 'hqx' => 'application/mac-binhex40',
  2048. 'cpt' => 'application/mac-compactpro',
  2049. 'doc' => 'application/msword',
  2050. 'bin' => 'application/macbinary',
  2051. 'dms' => 'application/octet-stream',
  2052. 'lha' => 'application/octet-stream',
  2053. 'lzh' => 'application/octet-stream',
  2054. 'exe' => 'application/octet-stream',
  2055. 'class' => 'application/octet-stream',
  2056. 'psd' => 'application/octet-stream',
  2057. 'so' => 'application/octet-stream',
  2058. 'sea' => 'application/octet-stream',
  2059. 'dll' => 'application/octet-stream',
  2060. 'oda' => 'application/oda',
  2061. 'pdf' => 'application/pdf',
  2062. 'ai' => 'application/postscript',
  2063. 'eps' => 'application/postscript',
  2064. 'ps' => 'application/postscript',
  2065. 'smi' => 'application/smil',
  2066. 'smil' => 'application/smil',
  2067. 'mif' => 'application/vnd.mif',
  2068. 'xls' => 'application/vnd.ms-excel',
  2069. 'ppt' => 'application/vnd.ms-powerpoint',
  2070. 'wbxml' => 'application/vnd.wap.wbxml',
  2071. 'wmlc' => 'application/vnd.wap.wmlc',
  2072. 'dcr' => 'application/x-director',
  2073. 'dir' => 'application/x-director',
  2074. 'dxr' => 'application/x-director',
  2075. 'dvi' => 'application/x-dvi',
  2076. 'gtar' => 'application/x-gtar',
  2077. 'php' => 'application/x-httpd-php',
  2078. 'php4' => 'application/x-httpd-php',
  2079. 'php3' => 'application/x-httpd-php',
  2080. 'phtml' => 'application/x-httpd-php',
  2081. 'phps' => 'application/x-httpd-php-source',
  2082. 'js' => 'application/x-javascript',
  2083. 'swf' => 'application/x-shockwave-flash',
  2084. 'sit' => 'application/x-stuffit',
  2085. 'tar' => 'application/x-tar',
  2086. 'tgz' => 'application/x-tar',
  2087. 'xhtml' => 'application/xhtml+xml',
  2088. 'xht' => 'application/xhtml+xml',
  2089. 'zip' => 'application/zip',
  2090. 'mid' => 'audio/midi',
  2091. 'midi' => 'audio/midi',
  2092. 'mpga' => 'audio/mpeg',
  2093. 'mp2' => 'audio/mpeg',
  2094. 'mp3' => 'audio/mpeg',
  2095. 'aif' => 'audio/x-aiff',
  2096. 'aiff' => 'audio/x-aiff',
  2097. 'aifc' => 'audio/x-aiff',
  2098. 'ram' => 'audio/x-pn-realaudio',
  2099. 'rm' => 'audio/x-pn-realaudio',
  2100. 'rpm' => 'audio/x-pn-realaudio-plugin',
  2101. 'ra' => 'audio/x-realaudio',
  2102. 'rv' => 'video/vnd.rn-realvideo',
  2103. 'wav' => 'audio/x-wav',
  2104. 'bmp' => 'image/bmp',
  2105. 'gif' => 'image/gif',
  2106. 'jpeg' => 'image/jpeg',
  2107. 'jpg' => 'image/jpeg',
  2108. 'jpe' => 'image/jpeg',
  2109. 'png' => 'image/png',
  2110. 'tiff' => 'image/tiff',
  2111. 'tif' => 'image/tiff',
  2112. 'css' => 'text/css',
  2113. 'html' => 'text/html',
  2114. 'htm' => 'text/html',
  2115. 'shtml' => 'text/html',
  2116. 'txt' => 'text/plain',
  2117. 'text' => 'text/plain',
  2118. 'log' => 'text/plain',
  2119. 'rtx' => 'text/richtext',
  2120. 'rtf' => 'text/rtf',
  2121. 'xml' => 'text/xml',
  2122. 'xsl' => 'text/xml',
  2123. 'mpeg' => 'video/mpeg',
  2124. 'mpg' => 'video/mpeg',
  2125. 'mpe' => 'video/mpeg',
  2126. 'qt' => 'video/quicktime',
  2127. 'mov' => 'video/quicktime',
  2128. 'avi' => 'video/x-msvideo',
  2129. 'movie' => 'video/x-sgi-movie',
  2130. 'doc' => 'application/msword',
  2131. 'word' => 'application/msword',
  2132. 'xl' => 'application/excel',
  2133. 'eml' => 'message/rfc822'
  2134. );
  2135. return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
  2136. }
  2137. /**
  2138. * Set (or reset) Class Objects (variables)
  2139. *
  2140. * Usage Example:
  2141. * $page->set('X-Priority', '3');
  2142. *
  2143. * @access public
  2144. * @param string $name Parameter Name
  2145. * @param mixed $value Parameter Value
  2146. * NOTE: will not work with arrays, there are no arrays to set/reset
  2147. * @todo Should this not be using __set() magic function?
  2148. */
  2149. public function set($name, $value = '') {
  2150. try {
  2151. if (isset($this->$name) ) {
  2152. $this->$name = $value;
  2153. } else {
  2154. throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL);
  2155. }
  2156. } catch (Exception $e) {
  2157. $this->SetError($e->getMessage());
  2158. if ($e->getCode() == self::STOP_CRITICAL) {
  2159. return false;
  2160. }
  2161. }
  2162. return true;
  2163. }
  2164. /**
  2165. * Strips newlines to prevent header injection.
  2166. * @access public
  2167. * @param string $str String
  2168. * @return string
  2169. */
  2170. public function SecureHeader($str) {
  2171. $str = str_replace("\r", '', $str);
  2172. $str = str_replace("\n", '', $str);
  2173. return trim($str);
  2174. }
  2175. /**
  2176. * Set the private key file and password to sign the message.
  2177. *
  2178. * @access public
  2179. * @param string $key_filename Parameter File Name
  2180. * @param string $key_pass Password for private key
  2181. */
  2182. public function Sign($cert_filename, $key_filename, $key_pass) {
  2183. $this->sign_cert_file = $cert_filename;
  2184. $this->sign_key_file = $key_filename;
  2185. $this->sign_key_pass = $key_pass;
  2186. }
  2187. /**
  2188. * Set the private key file and password to sign the message.
  2189. *
  2190. * @access public
  2191. * @param string $key_filename Parameter File Name
  2192. * @param string $key_pass Password for private key
  2193. */
  2194. public function DKIM_QP($txt) {
  2195. $tmp = '';
  2196. $line = '';
  2197. for ($i = 0; $i < strlen($txt); $i++) {
  2198. $ord = ord($txt[$i]);
  2199. if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
  2200. $line .= $txt[$i];
  2201. } else {
  2202. $line .= "=".sprintf("%02X", $ord);
  2203. }
  2204. }
  2205. return $line;
  2206. }
  2207. /**
  2208. * Generate DKIM signature
  2209. *
  2210. * @access public
  2211. * @param string $s Header
  2212. */
  2213. public function DKIM_Sign($s) {
  2214. $privKeyStr = file_get_contents($this->DKIM_private);
  2215. if ($this->DKIM_passphrase != '') {
  2216. $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  2217. } else {
  2218. $privKey = $privKeyStr;
  2219. }
  2220. if (openssl_sign($s, $signature, $privKey)) {
  2221. return base64_encode($signature);
  2222. }
  2223. }
  2224. /**
  2225. * Generate DKIM Canonicalization Header
  2226. *
  2227. * @access public
  2228. * @param string $s Header
  2229. */
  2230. public function DKIM_HeaderC($s) {
  2231. $s = preg_replace("/\r\n\s+/", " ", $s);
  2232. $lines = explode("\r\n", $s);
  2233. foreach ($lines as $key => $line) {
  2234. list($heading, $value) = explode(":", $line, 2);
  2235. $heading = strtolower($heading);
  2236. $value = preg_replace("/\s+/", " ", $value) ; // Compress useless spaces
  2237. $lines[$key] = $heading.":".trim($value) ; // Don't forget to remove WSP around the value
  2238. }
  2239. $s = implode("\r\n", $lines);
  2240. return $s;
  2241. }
  2242. /**
  2243. * Generate DKIM Canonicalization Body
  2244. *
  2245. * @access public
  2246. * @param string $body Message Body
  2247. */
  2248. public function DKIM_BodyC($body) {
  2249. if ($body == '') return "\r\n";
  2250. // stabilize line endings
  2251. $body = str_replace("\r\n", "\n", $body);
  2252. $body = str_replace("\n", "\r\n", $body);
  2253. // END stabilize line endings
  2254. while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
  2255. $body = substr($body, 0, strlen($body) - 2);
  2256. }
  2257. return $body;
  2258. }
  2259. /**
  2260. * Create the DKIM header, body, as new header
  2261. *
  2262. * @access public
  2263. * @param string $headers_line Header lines
  2264. * @param string $subject Subject
  2265. * @param string $body Body
  2266. */
  2267. public function DKIM_Add($headers_line, $subject, $body) {
  2268. $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
  2269. $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  2270. $DKIMquery = 'dns/txt'; // Query method
  2271. $DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  2272. $subject_header = "Subject: $subject";
  2273. $headers = explode($this->LE, $headers_line);
  2274. foreach($headers as $header) {
  2275. if (strpos($header, 'From:') === 0) {
  2276. $from_header = $header;
  2277. } elseif (strpos($header, 'To:') === 0) {
  2278. $to_header = $header;
  2279. }
  2280. }
  2281. $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  2282. $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  2283. $subject = str_replace('|', '=7C', $this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable
  2284. $body = $this->DKIM_BodyC($body);
  2285. $DKIMlen = strlen($body) ; // Length of body
  2286. $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body
  2287. $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";";
  2288. $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n".
  2289. "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n".
  2290. "\th=From:To:Subject;\r\n".
  2291. "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n".
  2292. "\tz=$from\r\n".
  2293. "\t|$to\r\n".
  2294. "\t|$subject;\r\n".
  2295. "\tbh=" . $DKIMb64 . ";\r\n".
  2296. "\tb=";
  2297. $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
  2298. $signed = $this->DKIM_Sign($toSign);
  2299. return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n".$dkimhdrs.$signed."\r\n";
  2300. }
  2301. protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body) {
  2302. if (!empty($this->action_function) && function_exists($this->action_function)) {
  2303. $params = array($isSent, $to, $cc, $bcc, $subject, $body);
  2304. call_user_func_array($this->action_function, $params);
  2305. }
  2306. }
  2307. }
  2308. class phpmailerException extends Exception {
  2309. public function errorMessage() {
  2310. $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  2311. return $errorMsg;
  2312. }
  2313. }
  2314. ?>