EmailLib.php 18 KB

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