PageRenderTime 66ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/class-phpmailer.php

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