EmailLib.php 17 KB

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