EmailLib.php 17 KB

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