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

/common/include/mailer/class.phpmailer.php

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