EmailLib.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. <?php
  2. App::uses('CakeEmail', 'Network/Email');
  3. App::uses('CakeLog', 'Log');
  4. App::uses('Utility', 'Tools.Utility');
  5. App::uses('MimeLib', 'Tools.Lib');
  6. App::uses('CakeText', 'Utility');
  7. // Support BC (snake case config)
  8. if (!Configure::read('Config.systemEmail')) {
  9. Configure::write('Config.systemEmail', Configure::read('Config.system_email'));
  10. }
  11. if (!Configure::read('Config.systemName')) {
  12. Configure::write('Config.systemName', Configure::read('Config.system_name'));
  13. }
  14. if (!Configure::read('Config.adminEmail')) {
  15. Configure::write('Config.adminEmail', Configure::read('Config.admin_email'));
  16. }
  17. if (!Configure::read('Config.adminName')) {
  18. Configure::write('Config.adminName', Configure::read('Config.admin_name'));
  19. }
  20. /**
  21. * Convenience class for internal mailer.
  22. *
  23. * Adds some useful features and fixes some bugs:
  24. * - enable easier attachment adding (and also from blob)
  25. * - enable embedded images in html mails
  26. * - extensive logging and error tracing
  27. * - create mails with blob attachments (embedded or attached)
  28. * - allow wrapLength to be adjusted
  29. * - Configure::read('Config.xMailer') can modify the x-mailer
  30. * - basic validation supported
  31. * - allow priority to be set (1 to 5)
  32. *
  33. * Configs for auto-from can be set via Configure::read('Config.adminEmail').
  34. * For systemEmail() one also needs Configure value Config.systemEmail to be set.
  35. *
  36. * @author Mark Scherer
  37. * @license http://opensource.org/licenses/mit-license.php MIT
  38. */
  39. class EmailLib extends CakeEmail {
  40. protected $_log = null;
  41. protected $_debug = null;
  42. protected $_error = null;
  43. protected $_wrapLength = null;
  44. protected $_priority = null;
  45. public function __construct($config = null) {
  46. if ($config === null) {
  47. $config = Configure::read('Email.config') ?: 'default';
  48. }
  49. parent::__construct($config);
  50. $this->reset($config);
  51. }
  52. /**
  53. * Quick way to send emails to admin.
  54. * App::uses() + EmailLib::systemEmail()
  55. *
  56. * Note: always go out with default settings (e.g.: SMTP even if debug > 0)
  57. *
  58. * @param string $subject
  59. * @param string $message
  60. * @param string $transportConfig
  61. * @return bool Success
  62. */
  63. public static function systemEmail($subject, $message = 'System Email', $transportConfig = null) {
  64. $class = __CLASS__;
  65. $instance = new $class($transportConfig);
  66. $instance->from(Configure::read('Config.systemEmail'), Configure::read('Config.systemName'));
  67. $instance->to(Configure::read('Config.adminEmail'), Configure::read('Config.adminName'));
  68. if ($subject !== null) {
  69. $instance->subject($subject);
  70. }
  71. if (is_array($message)) {
  72. $instance->viewVars($message);
  73. $message = null;
  74. } elseif ($message === null && array_key_exists('message', $config = $instance->config())) {
  75. $message = $config['message'];
  76. }
  77. return $instance->send($message);
  78. }
  79. /**
  80. * Change the layout
  81. *
  82. * @param string $layout Layout to use (or false to use none)
  83. * @return resource EmailLib
  84. */
  85. public function layout($layout = false) {
  86. if ($layout !== false) {
  87. $this->_layout = $layout;
  88. }
  89. return $this;
  90. }
  91. /**
  92. * Add an attachment from file
  93. *
  94. * @param string $file: absolute path
  95. * @param string $filename
  96. * @param array $fileInfo
  97. * @return resource EmailLib
  98. */
  99. public function addAttachment($file, $name = null, $fileInfo = []) {
  100. $fileInfo['file'] = $file;
  101. if (!empty($name)) {
  102. $fileInfo = [$name => $fileInfo];
  103. } else {
  104. $fileInfo = [$fileInfo];
  105. }
  106. return $this->addAttachments($fileInfo);
  107. }
  108. /**
  109. * Add an attachment as blob
  110. *
  111. * @param binary $content: blob data
  112. * @param string $filename to attach it
  113. * @param string $mimeType (leave it empty to get mimetype from $filename)
  114. * @param array $fileInfo
  115. * @return resource EmailLib
  116. */
  117. public function addBlobAttachment($content, $filename, $mimeType = null, $fileInfo = []) {
  118. if ($mimeType === null) {
  119. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  120. $mimeType = $this->_getMimeByExtension($ext);
  121. }
  122. $fileInfo['content'] = $content;
  123. $fileInfo['mimetype'] = $mimeType;
  124. $file = [$filename => $fileInfo];
  125. return $this->addAttachments($file);
  126. }
  127. /**
  128. * Add an inline attachment from file
  129. *
  130. * Options:
  131. * - mimetype
  132. * - contentDisposition
  133. *
  134. * @param string $file: absolute path
  135. * @param string $filename (optional)
  136. * @param string $contentId (optional)
  137. * @param array $options Options
  138. * @return mixed resource $EmailLib or string $contentId
  139. */
  140. public function addEmbeddedAttachment($file, $name = null, $contentId = null, $options = []) {
  141. if (empty($name)) {
  142. $name = basename($file);
  143. }
  144. $name = pathinfo($name, PATHINFO_FILENAME) . '_' . md5($file) . '.' . pathinfo($name, PATHINFO_EXTENSION);
  145. if ($contentId === null && ($cid = $this->_isEmbeddedAttachment($file, $name))) {
  146. return $cid;
  147. }
  148. $options['file'] = $file;
  149. if (empty($options['mimetype'])) {
  150. $options['mimetype'] = $this->_getMime($file);
  151. }
  152. $options['contentId'] = $contentId ? $contentId : str_replace('-', '', CakeText::uuid()) . '@' . $this->_domain;
  153. $file = [$name => $options];
  154. $res = $this->addAttachments($file);
  155. if ($contentId === null) {
  156. return $options['contentId'];
  157. }
  158. return $res;
  159. }
  160. /**
  161. * Add an inline attachment as blob
  162. *
  163. * Options:
  164. * - contentDisposition
  165. *
  166. * @param binary $content: blob data
  167. * @param string $filename to attach it
  168. * @param string $mimeType (leave it empty to get mimetype from $filename)
  169. * @param string $contentId (optional)
  170. * @param array $options Options
  171. * @return mixed resource $EmailLib or string $contentId
  172. */
  173. public function addEmbeddedBlobAttachment($content, $filename, $mimeType = null, $contentId = null, $options = []) {
  174. if ($mimeType === null) {
  175. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  176. $mimeType = $this->_getMimeByExtension($ext);
  177. }
  178. $filename = pathinfo($filename, PATHINFO_FILENAME) . '_' . md5($content) . '.' . pathinfo($filename, PATHINFO_EXTENSION);
  179. if ($contentId === null && ($cid = $this->_isEmbeddedBlobAttachment($content, $filename))) {
  180. return $cid;
  181. }
  182. $options['content'] = $content;
  183. $options['mimetype'] = $mimeType;
  184. $options['contentId'] = $contentId ? $contentId : str_replace('-', '', CakeText::uuid()) . '@' . $this->_domain;
  185. $file = [$filename => $options];
  186. $res = $this->addAttachments($file);
  187. if ($contentId === null) {
  188. return $options['contentId'];
  189. }
  190. return $res;
  191. }
  192. /**
  193. * Returns if this particular file has already been attached as embedded file with this exact name
  194. * to prevent the same image to overwrite each other and also to only send this image once.
  195. * Allows multiple usage of the same embedded image (using the same cid)
  196. *
  197. * @param string $file
  198. * @param string $name
  199. * @return string cid of the found file or false if no such attachment can be found
  200. */
  201. protected function _isEmbeddedAttachment($file, $name) {
  202. foreach ($this->_attachments as $filename => $fileInfo) {
  203. if ($filename !== $name) {
  204. continue;
  205. }
  206. return $fileInfo['contentId'];
  207. }
  208. return false;
  209. }
  210. /**
  211. * Returns if this particular file has already been attached as embedded file with this exact name
  212. * to prevent the same image to overwrite each other and also to only send this image once.
  213. * Allows multiple usage of the same embedded image (using the same cid)
  214. *
  215. * @return string cid of the found file or false if no such attachment can be found
  216. */
  217. protected function _isEmbeddedBlobAttachment($content, $name) {
  218. foreach ($this->_attachments as $filename => $fileInfo) {
  219. if ($filename !== $name) {
  220. continue;
  221. }
  222. return $fileInfo['contentId'];
  223. }
  224. return false;
  225. }
  226. /**
  227. * Try to determine the mimetype by filename.
  228. * Uses finfo_open() if availble, otherwise guesses it via file extension.
  229. *
  230. * @param string $filename
  231. * @return string Mimetype
  232. */
  233. protected function _getMime($filename) {
  234. $mimeType = Utility::getMimeType($filename);
  235. if (!$mimeType) {
  236. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  237. $mimeType = $this->_getMimeByExtension($ext);
  238. }
  239. return $mimeType;
  240. }
  241. /**
  242. * Try to find mimetype by file extension
  243. *
  244. * @param string $ext lowercase (jpg, png, pdf, ...)
  245. * @param string $defaultMimeType
  246. * @return string Mimetype (falls back to `application/octet-stream`)
  247. */
  248. protected function _getMimeByExtension($ext, $default = 'application/octet-stream') {
  249. if (!$ext) {
  250. return $default;
  251. }
  252. if (!isset($this->_Mime)) {
  253. $this->_Mime = new MimeLib();
  254. }
  255. $mime = $this->_Mime->getMimeType($ext);
  256. if (!$mime) {
  257. $mime = $default;
  258. }
  259. return $mime;
  260. }
  261. /**
  262. * Read the file contents and return a base64 version of the file contents.
  263. * Overwrite parent to avoid File class and file_exists to false negative existent
  264. * remove images.
  265. * Also fixes file_get_contents (used via File class) to close the connection again
  266. * after getting remote files. So far it would have kept the connection open in HTTP/1.1.
  267. *
  268. * @param string $path The absolute path to the file to read.
  269. * @return string File contents in base64 encoding
  270. */
  271. protected function _readFile($path) {
  272. $context = stream_context_create(
  273. ['http' => ['header' => 'Connection: close']]);
  274. $content = file_get_contents($path, 0, $context);
  275. if (!$content) {
  276. trigger_error('No content found for ' . $path);
  277. }
  278. return chunk_split(base64_encode($content));
  279. }
  280. /**
  281. * Validate if the email has the required fields necessary to make send() work.
  282. * Assumes layouting (does not check on content to be present or if view/layout files are missing).
  283. *
  284. * @return bool Success
  285. */
  286. public function validates() {
  287. if (!empty($this->_subject) && !empty($this->_to)) {
  288. return true;
  289. }
  290. return false;
  291. }
  292. /**
  293. * Attach inline/embedded files to the message.
  294. *
  295. * CUSTOM FIX: blob data support
  296. *
  297. * @override
  298. * @param string $boundary Boundary to use. If null, will default to $this->_boundary
  299. * @return array An array of lines to add to the message
  300. */
  301. protected function _attachInlineFiles($boundary = null) {
  302. if ($boundary === null) {
  303. $boundary = $this->_boundary;
  304. }
  305. $msg = [];
  306. foreach ($this->_attachments as $filename => $fileInfo) {
  307. if (empty($fileInfo['contentId'])) {
  308. continue;
  309. }
  310. if (!empty($fileInfo['content'])) {
  311. $data = $fileInfo['content'];
  312. $data = chunk_split(base64_encode($data));
  313. } elseif (!empty($fileInfo['file'])) {
  314. $data = $this->_readFile($fileInfo['file']);
  315. } else {
  316. continue;
  317. }
  318. $msg[] = '--' . $boundary;
  319. $msg[] = 'Content-Type: ' . $fileInfo['mimetype'];
  320. $msg[] = 'Content-Transfer-Encoding: base64';
  321. $msg[] = 'Content-ID: <' . $fileInfo['contentId'] . '>';
  322. $msg[] = 'Content-Disposition: inline; filename="' . $filename . '"';
  323. $msg[] = '';
  324. $msg[] = $data;
  325. $msg[] = '';
  326. }
  327. return $msg;
  328. }
  329. /**
  330. * Attach non-embedded files by adding file contents inside boundaries.
  331. *
  332. * CUSTOM FIX: blob data support
  333. *
  334. * @override
  335. * @param string $boundary Boundary to use. If null, will default to $this->_boundary
  336. * @return array An array of lines to add to the message
  337. */
  338. protected function _attachFiles($boundary = null) {
  339. if ($boundary === null) {
  340. $boundary = $this->_boundary;
  341. }
  342. $msg = [];
  343. foreach ($this->_attachments as $filename => $fileInfo) {
  344. if (!empty($fileInfo['contentId'])) {
  345. continue;
  346. }
  347. if (!empty($fileInfo['content'])) {
  348. $data = $fileInfo['content'];
  349. $data = chunk_split(base64_encode($data));
  350. } elseif (!empty($fileInfo['file'])) {
  351. $data = $this->_readFile($fileInfo['file']);
  352. } else {
  353. continue;
  354. }
  355. $msg[] = '--' . $boundary;
  356. $msg[] = 'Content-Type: ' . $fileInfo['mimetype'];
  357. $msg[] = 'Content-Transfer-Encoding: base64';
  358. if (
  359. !isset($fileInfo['contentDisposition']) ||
  360. $fileInfo['contentDisposition']
  361. ) {
  362. $msg[] = 'Content-Disposition: attachment; filename="' . $filename . '"';
  363. }
  364. $msg[] = '';
  365. $msg[] = $data;
  366. $msg[] = '';
  367. }
  368. return $msg;
  369. }
  370. /**
  371. * Add attachments to the email message
  372. *
  373. * CUSTOM FIX: Allow URLs
  374. * CUSTOM FIX: Blob data support
  375. *
  376. * Attachments can be defined in a few forms depending on how much control you need:
  377. *
  378. * Attach a single file:
  379. *
  380. * {{{
  381. * $email->attachments('path/to/file');
  382. * }}}
  383. *
  384. * Attach a file with a different filename:
  385. *
  386. * {{{
  387. * $email->attachments(array('custom_name.txt' => 'path/to/file.txt'));
  388. * }}}
  389. *
  390. * Attach a file and specify additional properties:
  391. *
  392. * {{{
  393. * $email->attachments(array('custom_name.png' => array(
  394. * 'file' => 'path/to/file',
  395. * 'mimetype' => 'image/png',
  396. * 'contentId' => 'abc123'
  397. * ));
  398. * }}}
  399. *
  400. * The `contentId` key allows you to specify an inline attachment. In your email text, you
  401. * can use `<img src="cid:abc123" />` to display the image inline.
  402. *
  403. * @override
  404. * @param mixed $attachments String with the filename or array with filenames
  405. * @return mixed Either the array of attachments when getting or $this when setting.
  406. * @throws SocketException
  407. */
  408. public function attachments($attachments = null) {
  409. if ($attachments === null) {
  410. return $this->_attachments;
  411. }
  412. $attach = [];
  413. foreach ((array)$attachments as $name => $fileInfo) {
  414. if (!is_array($fileInfo)) {
  415. $fileInfo = ['file' => $fileInfo];
  416. }
  417. if (empty($fileInfo['content'])) {
  418. if (!isset($fileInfo['file'])) {
  419. throw new SocketException('File not specified.');
  420. }
  421. $fileName = $fileInfo['file'];
  422. if (!preg_match('~^https?://~i', $fileInfo['file'])) {
  423. $fileInfo['file'] = realpath($fileInfo['file']);
  424. }
  425. if ($fileInfo['file'] === false || !Utility::fileExists($fileInfo['file'])) {
  426. throw new SocketException(sprintf('File not found: "%s"', $fileName));
  427. }
  428. if (is_int($name)) {
  429. $name = basename($fileInfo['file']);
  430. }
  431. }
  432. if (empty($fileInfo['mimetype'])) {
  433. $ext = pathinfo($name, PATHINFO_EXTENSION);
  434. $fileInfo['mimetype'] = $this->_getMimeByExtension($ext);
  435. }
  436. $attach[$name] = $fileInfo;
  437. }
  438. $this->_attachments = $attach;
  439. return $this;
  440. }
  441. /**
  442. * Set the body of the mail as we send it.
  443. * Note: the text can be an array, each element will appear as a seperate line in the message body.
  444. *
  445. * Do NOT pass a message if you use $this->set() in combination with templates
  446. *
  447. * @overwrite
  448. * @param string/array: message
  449. * @return bool Success
  450. */
  451. public function send($message = null) {
  452. $this->_log = [
  453. 'to' => $this->_to,
  454. 'from' => $this->_from,
  455. 'sender' => $this->_sender,
  456. 'replyTo' => $this->_replyTo,
  457. 'cc' => $this->_cc,
  458. 'subject' => $this->_subject,
  459. 'bcc' => $this->_bcc,
  460. 'transport' => $this->_transportName
  461. ];
  462. if ($this->_priority) {
  463. $this->_headers['X-Priority'] = $this->_priority;
  464. //$this->_headers['X-MSMail-Priority'] = 'High';
  465. //$this->_headers['Importance'] = 'High';
  466. }
  467. // Security measure to not sent to the actual addressee in debug mode while email sending is live
  468. if (Configure::read('debug') && Configure::read('Email.live')) {
  469. $adminEmail = Configure::read('Config.adminEmail');
  470. if (!$adminEmail) {
  471. $adminEmail = Configure::read('Config.systemEmail');
  472. }
  473. foreach ($this->_to as $k => $v) {
  474. if ($k === $adminEmail) {
  475. continue;
  476. }
  477. unset($this->_to[$k]);
  478. $this->_to[$adminEmail] = $v;
  479. }
  480. foreach ($this->_cc as $k => $v) {
  481. if ($k === $adminEmail) {
  482. continue;
  483. }
  484. unset($this->_cc[$k]);
  485. $this->_cc[$adminEmail] = $v;
  486. }
  487. foreach ($this->_bcc as $k => $v) {
  488. if ($k === $adminEmail) {
  489. continue;
  490. }
  491. unset($this->_bcc[$k]);
  492. $this->_bcc[] = $v;
  493. }
  494. }
  495. try {
  496. $this->_debug = parent::send($message);
  497. } catch (Exception $e) {
  498. $this->_error = $e->getMessage();
  499. $this->_error .= ' (line ' . $e->getLine() . ' in ' . $e->getFile() . ')' . PHP_EOL .
  500. $e->getTraceAsString();
  501. if (!empty($this->_config['logReport'])) {
  502. $this->_logEmail();
  503. } else {
  504. CakeLog::write('error', $this->_error);
  505. }
  506. return false;
  507. }
  508. if (!empty($this->_config['logReport'])) {
  509. $this->_logEmail();
  510. }
  511. return true;
  512. }
  513. /**
  514. * Allow modifications of the message
  515. *
  516. * @param string $text
  517. * @return string Text
  518. */
  519. protected function _prepMessage($text) {
  520. return $text;
  521. }
  522. /**
  523. * Returns the error if existent
  524. *
  525. * @return string
  526. */
  527. public function getError() {
  528. return $this->_error;
  529. }
  530. /**
  531. * Returns the log if existent
  532. *
  533. * @return string
  534. */
  535. public function getLog() {
  536. return $this->_log;
  537. }
  538. /**
  539. * Returns the debug content returned by send()
  540. *
  541. * @return string
  542. */
  543. public function getDebug() {
  544. return $this->_debug;
  545. }
  546. /**
  547. * Set/Get wrapLength
  548. *
  549. * @param int $length Must not be more than CakeEmail::LINE_LENGTH_MUST
  550. * @return int|CakeEmail
  551. */
  552. public function wrapLength($length = null) {
  553. if ($length === null) {
  554. return $this->_wrapLength;
  555. }
  556. $this->_wrapLength = $length;
  557. return $this;
  558. }
  559. /**
  560. * Set/Get priority
  561. *
  562. * @param int $priority 1 (highest) to 5 (lowest)
  563. * @return int|CakeEmail
  564. */
  565. public function priority($priority = null) {
  566. if ($priority === null) {
  567. return $this->_priority;
  568. }
  569. $this->_priority = $priority;
  570. return $this;
  571. }
  572. /**
  573. * Fix line length
  574. *
  575. * @overwrite
  576. * @param string $message Message to wrap
  577. * @return array Wrapped message
  578. */
  579. protected function _wrap($message, $wrapLength = CakeEmail::LINE_LENGTH_MUST) {
  580. if ($this->_wrapLength !== null) {
  581. $wrapLength = $this->_wrapLength;
  582. }
  583. return parent::_wrap($message, $wrapLength);
  584. }
  585. /**
  586. * Logs Email to type email
  587. *
  588. * @return void
  589. */
  590. protected function _logEmail($append = null) {
  591. $res = $this->_log['transport'] .
  592. ' - ' . 'TO:' . implode(',', array_keys($this->_log['to'])) .
  593. '||FROM:' . implode(',', array_keys($this->_log['from'])) .
  594. '||REPLY:' . implode(',', array_keys($this->_log['replyTo'])) .
  595. '||S:' . $this->_log['subject'];
  596. $type = 'email';
  597. if (!empty($this->_error)) {
  598. $type = 'email_error';
  599. $res .= '||ERROR:' . $this->_error;
  600. }
  601. if ($append) {
  602. $res .= '||' . $append;
  603. }
  604. CakeLog::write($type, $res);
  605. }
  606. /**
  607. * EmailLib::resetAndSet()
  608. *
  609. * @return void
  610. */
  611. public function reset($config = null) {
  612. if ($config === null) {
  613. $config = Configure::read('Email.config') ?: 'default';
  614. }
  615. parent::reset();
  616. $this->_priority = null;
  617. $this->_wrapLength = null;
  618. $this->_log = null;
  619. $this->_error = null;
  620. $this->_debug = null;
  621. $this->_config = (array)Configure::read('Email');
  622. $this->_applyConfig($config);
  623. if ($fromEmail = Configure::read('Config.systemEmail')) {
  624. $fromName = Configure::read('Config.systemName');
  625. } else {
  626. $fromEmail = Configure::read('Config.adminEmail');
  627. $fromName = Configure::read('Config.adminName');
  628. }
  629. if (!$fromEmail) {
  630. throw new RuntimeException('You need to either define Config.systemEmail or Config.adminEmail in Configure.');
  631. }
  632. $this->from($fromEmail, $fromName);
  633. if ($xMailer = Configure::read('Config.xMailer')) {
  634. $this->addHeaders(['X-Mailer' => $xMailer]);
  635. }
  636. }
  637. }