PageRenderTime 76ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/phpmailer/phpmailer/class.phpmailer.php

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