EmailLib.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. <?php
  2. App::uses('CakeEmail', 'Network/Email');
  3. App::uses('CakeLog', 'Log');
  4. if (!defined('BR')) {
  5. define('BR', '<br />');
  6. }
  7. /**
  8. * Convenience class for internal mailer.
  9. * Adds some nice features and fixes some bugs:
  10. * - enbale embedded images in html mails
  11. * - allow setting domain for CLI environment (now in core)
  12. * - enable easier attachment adding
  13. * - extensive logging and error tracing
  14. * - create mails with blob attachments (embedded or attached)
  15. * TODO: cleanup and more tests
  16. *
  17. * @author Mark Scherer
  18. * @license MIT
  19. * @cakephp 2.2
  20. * 2012-03-30 ms
  21. */
  22. class EmailLib extends CakeEmail {
  23. protected $_log = null;
  24. protected $_debug = null;
  25. protected $_error = null;
  26. public function __construct($config = null) {
  27. if ($config === null) {
  28. $config = 'default';
  29. }
  30. parent::__construct($config);
  31. $this->resetAndSet();
  32. }
  33. /**
  34. * quick way to send emails to admin
  35. * App::uses() + EmailLib::systemEmail()
  36. *
  37. * Note: always go out with default settings (e.g.: SMTP even if debug > 0)
  38. * @return bool $success
  39. * 2011-10-31 ms
  40. */
  41. public static function systemEmail($subject, $message = 'System Email', $transportConfig = null) {
  42. $class = __CLASS__;
  43. $instance = new $class($transportConfig);
  44. $instance->to(Configure::read('Config.admin_email'));
  45. $instance->from(Configure::read('Config.admin_email'));
  46. if ($subject !== null) {
  47. $instance->subject($subject);
  48. }
  49. if (is_array($message)) {
  50. $instance->viewVars($message);
  51. $message = null;
  52. } elseif ($message === null && array_key_exists('message', $config = $instance->config())) {
  53. $message = $config['message'];
  54. }
  55. if (true || $send === true) {
  56. return $instance->send($message);
  57. }
  58. return $instance;
  59. }
  60. /**
  61. * @param string $layout Layout to use (or false to use none)
  62. * @return resource EmailLib
  63. * 2011-11-02 ms
  64. */
  65. public function layout($layout = false) {
  66. if ($layout !== false) {
  67. $this->_layout = $layout;
  68. }
  69. return $this;
  70. }
  71. /**
  72. * @param string $file: absolute path
  73. * @param string $filename (optional)
  74. * @return resource EmailLib
  75. * 2011-11-02 ms
  76. */
  77. public function addAttachment($file, $name = null) {
  78. if (!empty($name)) {
  79. return $this->addAttachments(array($name=>$file));
  80. }
  81. return $this->addAttachments($file);
  82. }
  83. /**
  84. * @param binary $content: blob data
  85. * @param string $filename to attach it
  86. * @param string $mimeType (leave it empty to get mimetype from $filename)
  87. * @param string $contentId (optional)
  88. * @return mixed ressource EmailLib or string $contentId
  89. * 2011-11-02 ms
  90. */
  91. public function addBlobAttachment($content, $name, $mimeType = null) {
  92. $fileInfo = array();
  93. $fileInfo['content'] = $content;
  94. $fileInfo['mimetype'] = $mimeType;
  95. $file = array($name=>$fileInfo);
  96. $res = $this->addAttachments($file);
  97. if ($contentId === null) {
  98. return $fileInfo['contentId'];
  99. }
  100. return $res;
  101. }
  102. /**
  103. * @param binary $content: blob data
  104. * @param string $filename to attach it
  105. * @param string $mimeType (leave it empty to get mimetype from $filename)
  106. * @param string $contentId (optional)
  107. * @param array $options
  108. * - contentDisposition
  109. * @return mixed ressource $EmailLib or string $contentId
  110. * 2011-11-02 ms
  111. */
  112. public function addEmbeddedBlobAttachment($content, $name, $mimeType = null, $contentId = null, $options = array()) {
  113. $options['content'] = $content;
  114. $options['mimetype'] = $mimeType;
  115. $options['contentId'] = $contentId ? $contentId : str_replace('-', '', String::uuid()) . '@' . $this->_domain;
  116. $file = array($name => $options);
  117. $res = $this->addAttachments($file);
  118. if ($contentId === null) {
  119. return $options['contentId'];
  120. }
  121. return $res;
  122. }
  123. /**
  124. * @param string $file: absolute path
  125. * @param string $filename (optional)
  126. * @param string $contentId (optional)
  127. * @param array $options
  128. * - mimetype
  129. * - contentDisposition
  130. * @return mixed ressource $EmailLib or string $contentId
  131. * 2011-11-02 ms
  132. */
  133. public function addEmbeddedAttachment($file, $name = null, $contentId = null, $options = array()) {
  134. $path = realpath($file);
  135. if (empty($name)) {
  136. $name = basename($file);
  137. }
  138. if ($contentId === null && ($cid = $this->_isEmbeddedAttachment($path, $name))) {
  139. return $cid;
  140. }
  141. $options['file'] = $path;
  142. if (empty($options['mimetype'])) {
  143. $options['mimetype'] = $this->_getMime($file);
  144. }
  145. $options['contentId'] = $contentId ? $contentId : str_replace('-', '', String::uuid()) . '@' . $this->_domain;
  146. $file = array($name => $options);
  147. $res = $this->addAttachments($file);
  148. if ($contentId === null) {
  149. return $options['contentId'];
  150. }
  151. return $res;
  152. }
  153. /**
  154. * Returns if this particular file has already been attached as embedded file with this exact name
  155. * to prevent the same image to overwrite each other and also to only send this image once.
  156. * Allows multiple usage of the same embedded image (using the same cid)
  157. *
  158. * @return string cid of the found file or false if no such attachment can be found
  159. */
  160. protected function _isEmbeddedAttachment($file, $name) {
  161. foreach ($this->_attachments as $filename => $fileInfo) {
  162. if ($filename != $name) {
  163. continue;
  164. }
  165. if ($fileInfo['file'] == $file) {
  166. return $fileInfo['contentId'];
  167. }
  168. }
  169. return false;
  170. }
  171. protected function _getMime($filename) {
  172. if (function_exists('finfo_open')) {
  173. $finfo = finfo_open(FILEINFO_MIME);
  174. $mimetype = finfo_file($finfo, $filename);
  175. finfo_close($finfo);
  176. } else {
  177. //TODO: improve
  178. $ext = pathinfo($filename, PATHINFO_EXTENSION);
  179. $mimetype = $this->_getMimeByExtension($ext);
  180. }
  181. return $mimetype;
  182. }
  183. /**
  184. * try to find mimetype by file extension
  185. * @param string $ext lowercase (jpg, png, pdf, ...)
  186. * @param string $defaultMimeType
  187. * @return string $mimeType (falls back to )
  188. * 2012-04-17 ms
  189. */
  190. protected function _getMimeByExtension($ext, $default = 'application/octet-stream') {
  191. switch ($ext) {
  192. case "zip": $mime="application/zip"; break;
  193. case "ez": $mime="application/andrew-inset"; break;
  194. case "hqx": $mime="application/mac-binhex40"; break;
  195. case "cpt": $mime="application/mac-compactpro"; break;
  196. case "doc": $mime="application/msword"; break;
  197. case "bin": $mime="application/octet-stream"; break;
  198. case "dms": $mime="application/octet-stream"; break;
  199. case "lha": $mime="application/octet-stream"; break;
  200. case "lzh": $mime="application/octet-stream"; break;
  201. case "exe": $mime="application/octet-stream"; break;
  202. case "class": $mime="application/octet-stream"; break;
  203. case "so": $mime="application/octet-stream"; break;
  204. case "dll": $mime="application/octet-stream"; break;
  205. case "oda": $mime="application/oda"; break;
  206. case "pdf": $mime="application/pdf"; break;
  207. case "ai": $mime="application/postscript"; break;
  208. case "eps": $mime="application/postscript"; break;
  209. case "ps": $mime="application/postscript"; break;
  210. case "smi": $mime="application/smil"; break;
  211. case "smil": $mime="application/smil"; break;
  212. case "xls": $mime="application/vnd.ms-excel"; break;
  213. case "ppt": $mime="application/vnd.ms-powerpoint"; break;
  214. case "wbxml": $mime="application/vnd.wap.wbxml"; break;
  215. case "wmlc": $mime="application/vnd.wap.wmlc"; break;
  216. case "wmlsc": $mime="application/vnd.wap.wmlscriptc"; break;
  217. case "bcpio": $mime="application/x-bcpio"; break;
  218. case "vcd": $mime="application/x-cdlink"; break;
  219. case "pgn": $mime="application/x-chess-pgn"; break;
  220. case "cpio": $mime="application/x-cpio"; break;
  221. case "csh": $mime="application/x-csh"; break;
  222. case "dcr": $mime="application/x-director"; break;
  223. case "dir": $mime="application/x-director"; break;
  224. case "dxr": $mime="application/x-director"; break;
  225. case "dvi": $mime="application/x-dvi"; break;
  226. case "spl": $mime="application/x-futuresplash"; break;
  227. case "gtar": $mime="application/x-gtar"; break;
  228. case "hdf": $mime="application/x-hdf"; break;
  229. case "js": $mime="application/x-javascript"; break;
  230. case "skp": $mime="application/x-koan"; break;
  231. case "skd": $mime="application/x-koan"; break;
  232. case "skt": $mime="application/x-koan"; break;
  233. case "skm": $mime="application/x-koan"; break;
  234. case "latex": $mime="application/x-latex"; break;
  235. case "nc": $mime="application/x-netcdf"; break;
  236. case "cdf": $mime="application/x-netcdf"; break;
  237. case "sh": $mime="application/x-sh"; break;
  238. case "shar": $mime="application/x-shar"; break;
  239. case "swf": $mime="application/x-shockwave-flash"; break;
  240. case "sit": $mime="application/x-stuffit"; break;
  241. case "sv4cpio": $mime="application/x-sv4cpio"; break;
  242. case "sv4crc": $mime="application/x-sv4crc"; break;
  243. case "tar": $mime="application/x-tar"; break;
  244. case "tcl": $mime="application/x-tcl"; break;
  245. case "tex": $mime="application/x-tex"; break;
  246. case "texinfo": $mime="application/x-texinfo"; break;
  247. case "texi": $mime="application/x-texinfo"; break;
  248. case "t": $mime="application/x-troff"; break;
  249. case "tr": $mime="application/x-troff"; break;
  250. case "roff": $mime="application/x-troff"; break;
  251. case "man": $mime="application/x-troff-man"; break;
  252. case "me": $mime="application/x-troff-me"; break;
  253. case "ms": $mime="application/x-troff-ms"; break;
  254. case "ustar": $mime="application/x-ustar"; break;
  255. case "src": $mime="application/x-wais-source"; break;
  256. case "xhtml": $mime="application/xhtml+xml"; break;
  257. case "xht": $mime="application/xhtml+xml"; break;
  258. case "zip": $mime="application/zip"; break;
  259. case "au": $mime="audio/basic"; break;
  260. case "snd": $mime="audio/basic"; break;
  261. case "mid": $mime="audio/midi"; break;
  262. case "midi": $mime="audio/midi"; break;
  263. case "kar": $mime="audio/midi"; break;
  264. case "mpga": $mime="audio/mpeg"; break;
  265. case "mp2": $mime="audio/mpeg"; break;
  266. case "mp3": $mime="audio/mpeg"; break;
  267. case "aif": $mime="audio/x-aiff"; break;
  268. case "aiff": $mime="audio/x-aiff"; break;
  269. case "aifc": $mime="audio/x-aiff"; break;
  270. case "m3u": $mime="audio/x-mpegurl"; break;
  271. case "ram": $mime="audio/x-pn-realaudio"; break;
  272. case "rm": $mime="audio/x-pn-realaudio"; break;
  273. case "rpm": $mime="audio/x-pn-realaudio-plugin"; break;
  274. case "ra": $mime="audio/x-realaudio"; break;
  275. case "wav": $mime="audio/x-wav"; break;
  276. case "pdb": $mime="chemical/x-pdb"; break;
  277. case "xyz": $mime="chemical/x-xyz"; break;
  278. case "bmp": $mime="image/bmp"; break;
  279. case "gif": $mime="image/gif"; break;
  280. case "ief": $mime="image/ief"; break;
  281. case "jpeg": $mime="image/jpeg"; break;
  282. case "jpg": $mime="image/jpeg"; break;
  283. case "jpe": $mime="image/jpeg"; break;
  284. case "png": $mime="image/png"; break;
  285. case "tiff": $mime="image/tiff"; break;
  286. case "tif": $mime="image/tiff"; break;
  287. case "djvu": $mime="image/vnd.djvu"; break;
  288. case "djv": $mime="image/vnd.djvu"; break;
  289. case "wbmp": $mime="image/vnd.wap.wbmp"; break;
  290. case "ras": $mime="image/x-cmu-raster"; break;
  291. case "pnm": $mime="image/x-portable-anymap"; break;
  292. case "pbm": $mime="image/x-portable-bitmap"; break;
  293. case "pgm": $mime="image/x-portable-graymap"; break;
  294. case "ppm": $mime="image/x-portable-pixmap"; break;
  295. case "rgb": $mime="image/x-rgb"; break;
  296. case "xbm": $mime="image/x-xbitmap"; break;
  297. case "xpm": $mime="image/x-xpixmap"; break;
  298. case "xwd": $mime="image/x-xwindowdump"; break;
  299. case "igs": $mime="model/iges"; break;
  300. case "iges": $mime="model/iges"; break;
  301. case "msh": $mime="model/mesh"; break;
  302. case "mesh": $mime="model/mesh"; break;
  303. case "silo": $mime="model/mesh"; break;
  304. case "wrl": $mime="model/vrml"; break;
  305. case "vrml": $mime="model/vrml"; break;
  306. case "css": $mime="text/css"; break;
  307. case "html": $mime="text/html"; break;
  308. case "htm": $mime="text/html"; break;
  309. case "asc": $mime="text/plain"; break;
  310. case "txt": $mime="text/plain"; break;
  311. case "rtx": $mime="text/richtext"; break;
  312. case "rtf": $mime="text/rtf"; break;
  313. case "sgml": $mime="text/sgml"; break;
  314. case "sgm": $mime="text/sgml"; break;
  315. case "tsv": $mime="text/tab-separated-values"; break;
  316. case "wml": $mime="text/vnd.wap.wml"; break;
  317. case "wmls": $mime="text/vnd.wap.wmlscript"; break;
  318. case "etx": $mime="text/x-setext"; break;
  319. case "xml": $mime="text/xml"; break;
  320. case "xsl": $mime="text/xml"; break;
  321. case "mpeg": $mime="video/mpeg"; break;
  322. case "mpg": $mime="video/mpeg"; break;
  323. case "mpe": $mime="video/mpeg"; break;
  324. case "qt": $mime="video/quicktime"; break;
  325. case "mov": $mime="video/quicktime"; break;
  326. case "mxu": $mime="video/vnd.mpegurl"; break;
  327. case "avi": $mime="video/x-msvideo"; break;
  328. case "movie": $mime="video/x-sgi-movie"; break;
  329. case "asf": $mime="video/x-ms-asf"; break;
  330. case "asx": $mime="video/x-ms-asf"; break;
  331. case "wm": $mime="video/x-ms-wm"; break;
  332. case "wmv": $mime="video/x-ms-wmv"; break;
  333. case "wvx": $mime="video/x-ms-wvx"; break;
  334. case "ice": $mime="x-conference/x-cooltalk"; break;
  335. }
  336. if (empty($mime)) {
  337. $mime = $default;
  338. }
  339. return $mime;
  340. }
  341. public function validates() {
  342. if (!empty($this->Email->subject)) {
  343. return true;
  344. }
  345. return false;
  346. }
  347. /**
  348. * Attach inline/embedded files to the message.
  349. * @override
  350. * CUSTOM FIX: blob data support
  351. *
  352. * @param string $boundary Boundary to use. If null, will default to $this->_boundary
  353. * @return array An array of lines to add to the message
  354. */
  355. protected function _attachInlineFiles($boundary = null) {
  356. if ($boundary === null) {
  357. $boundary = $this->_boundary;
  358. }
  359. $msg = array();
  360. foreach ($this->_attachments as $filename => $fileInfo) {
  361. if (empty($fileInfo['contentId'])) {
  362. continue;
  363. }
  364. if (!empty($fileInfo['content'])) {
  365. $data = $fileInfo['content'];
  366. $data = chunk_split(base64_encode($data));
  367. } elseif (!empty($fileInfo['file'])) {
  368. $data = $this->_readFile($fileInfo['file']);
  369. } else {
  370. continue;
  371. }
  372. $msg[] = '--' . $boundary;
  373. $msg[] = 'Content-Type: ' . $fileInfo['mimetype'];
  374. $msg[] = 'Content-Transfer-Encoding: base64';
  375. $msg[] = 'Content-ID: <' . $fileInfo['contentId'] . '>';
  376. $msg[] = 'Content-Disposition: inline; filename="' . $filename . '"';
  377. $msg[] = '';
  378. $msg[] = $data;
  379. $msg[] = '';
  380. }
  381. return $msg;
  382. }
  383. /**
  384. * Attach non-embedded files by adding file contents inside boundaries.
  385. * @override
  386. * CUSTOM FIX: blob data support
  387. *
  388. * @param string $boundary Boundary to use. If null, will default to $this->_boundary
  389. * @return array An array of lines to add to the message
  390. */
  391. protected function _attachFiles($boundary = null) {
  392. if ($boundary === null) {
  393. $boundary = $this->_boundary;
  394. }
  395. $msg = array();
  396. foreach ($this->_attachments as $filename => $fileInfo) {
  397. if (!empty($fileInfo['contentId'])) {
  398. continue;
  399. }
  400. if (!empty($fileInfo['content'])) {
  401. $data = $fileInfo['content'];
  402. $data = chunk_split(base64_encode($data));
  403. } elseif (!empty($fileInfo['file'])) {
  404. $data = $this->_readFile($fileInfo['file']);
  405. } else {
  406. continue;
  407. }
  408. $msg[] = '--' . $boundary;
  409. $msg[] = 'Content-Type: ' . $fileInfo['mimetype'];
  410. $msg[] = 'Content-Transfer-Encoding: base64';
  411. $msg[] = 'Content-Disposition: attachment; filename="' . $filename . '"';
  412. $msg[] = '';
  413. $msg[] = $data;
  414. $msg[] = '';
  415. }
  416. return $msg;
  417. }
  418. /**
  419. * Add attachments to the email message
  420. * @override
  421. * CUSTOM FIX: blob data support
  422. *
  423. * Attachments can be defined in a few forms depending on how much control you need:
  424. *
  425. * Attach a single file:
  426. *
  427. * {{{
  428. * $email->attachments('path/to/file');
  429. * }}}
  430. *
  431. * Attach a file with a different filename:
  432. *
  433. * {{{
  434. * $email->attachments(array('custom_name.txt' => 'path/to/file.txt'));
  435. * }}}
  436. *
  437. * Attach a file and specify additional properties:
  438. *
  439. * {{{
  440. * $email->attachments(array('custom_name.png' => array(
  441. * 'file' => 'path/to/file',
  442. * 'mimetype' => 'image/png',
  443. * 'contentId' => 'abc123'
  444. * ));
  445. * }}}
  446. *
  447. * The `contentId` key allows you to specify an inline attachment. In your email text, you
  448. * can use `<img src="cid:abc123" />` to display the image inline.
  449. *
  450. * @param mixed $attachments String with the filename or array with filenames
  451. * @return mixed Either the array of attachments when getting or $this when setting.
  452. * @throws SocketException
  453. */
  454. public function attachments($attachments = null) {
  455. if ($attachments === null) {
  456. return $this->_attachments;
  457. }
  458. $attach = array();
  459. foreach ((array)$attachments as $name => $fileInfo) {
  460. if (!is_array($fileInfo)) {
  461. $fileInfo = array('file' => $fileInfo);
  462. }
  463. if (empty($fileInfo['content'])) {
  464. if (!isset($fileInfo['file'])) {
  465. throw new SocketException(__d('cake_dev', 'File not specified.'));
  466. }
  467. $fileInfo['file'] = realpath($fileInfo['file']);
  468. if ($fileInfo['file'] === false || !file_exists($fileInfo['file'])) {
  469. throw new SocketException(__d('cake_dev', 'File not found: "%s"', $fileInfo['file']));
  470. }
  471. if (is_int($name)) {
  472. $name = basename($fileInfo['file']);
  473. }
  474. }
  475. if (empty($fileInfo['mimetype'])) {
  476. $ext = pathinfo($name, PATHINFO_EXTENSION);
  477. $fileInfo['mimetype'] = $this->_getMimeByExtension($ext);
  478. }
  479. $attach[$name] = $fileInfo;
  480. }
  481. $this->_attachments = $attach;
  482. return $this;
  483. }
  484. /**
  485. * Get list of headers
  486. * @override
  487. * CUSTOM FIX: message id correctly set in CLI and can be passed in via domain()
  488. *
  489. * ### Includes:
  490. *
  491. * - `from`
  492. * - `replyTo`
  493. * - `readReceipt`
  494. * - `returnPath`
  495. * - `to`
  496. * - `cc`
  497. * - `bcc`
  498. * - `subject`
  499. *
  500. * @param array $include
  501. * @return array
  502. */
  503. public function getHeaders($include = array()) {
  504. if ($include == array_values($include)) {
  505. $include = array_fill_keys($include, true);
  506. }
  507. $defaults = array_fill_keys(array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc', 'subject'), false);
  508. $include += $defaults;
  509. $headers = array();
  510. $relation = array(
  511. 'from' => 'From',
  512. 'replyTo' => 'Reply-To',
  513. 'readReceipt' => 'Disposition-Notification-To',
  514. 'returnPath' => 'Return-Path'
  515. );
  516. foreach ($relation as $var => $header) {
  517. if ($include[$var]) {
  518. $var = '_' . $var;
  519. $headers[$header] = current($this->_formatAddress($this->{$var}));
  520. }
  521. }
  522. if ($include['sender']) {
  523. if (key($this->_sender) === key($this->_from)) {
  524. $headers['Sender'] = '';
  525. } else {
  526. $headers['Sender'] = current($this->_formatAddress($this->_sender));
  527. }
  528. }
  529. foreach (array('to', 'cc', 'bcc') as $var) {
  530. if ($include[$var]) {
  531. $classVar = '_' . $var;
  532. $headers[ucfirst($var)] = implode(', ', $this->_formatAddress($this->{$classVar}));
  533. }
  534. }
  535. $headers += $this->_headers;
  536. if (!isset($headers['X-Mailer'])) {
  537. $headers['X-Mailer'] = self::EMAIL_CLIENT;
  538. }
  539. if (!isset($headers['Date'])) {
  540. $headers['Date'] = date(DATE_RFC2822);
  541. }
  542. if ($this->_messageId !== false) {
  543. if ($this->_messageId === true) {
  544. $headers['Message-ID'] = '<' . str_replace('-', '', String::UUID()) . '@' . $this->_domain . '>';
  545. } else {
  546. $headers['Message-ID'] = $this->_messageId;
  547. }
  548. }
  549. if ($include['subject']) {
  550. $headers['Subject'] = $this->_subject;
  551. }
  552. $headers['MIME-Version'] = '1.0';
  553. if (!empty($this->_attachments) || $this->_emailFormat === 'both') {
  554. $headers['Content-Type'] = 'multipart/mixed; boundary="' . $this->_boundary . '"';
  555. } elseif ($this->_emailFormat === 'text') {
  556. $headers['Content-Type'] = 'text/plain; charset=' . $this->charset;
  557. } elseif ($this->_emailFormat === 'html') {
  558. $headers['Content-Type'] = 'text/html; charset=' . $this->charset;
  559. }
  560. $headers['Content-Transfer-Encoding'] = $this->_getContentTransferEncoding();
  561. return $headers;
  562. }
  563. /**
  564. * Apply the config to an instance
  565. *
  566. * @param CakeEmail $obj CakeEmail
  567. * @param array $config
  568. * @return void
  569. * @throws ConfigureException When configuration file cannot be found, or is missing
  570. * the named config.
  571. */
  572. protected function _applyConfig($config) {
  573. if (is_string($config)) {
  574. if (!class_exists('EmailConfig') && !config('email')) {
  575. throw new ConfigureException(__d('cake_dev', '%s not found.', APP . 'Config' . DS . 'email.php'));
  576. }
  577. $configs = new EmailConfig();
  578. if (!isset($configs->{$config})) {
  579. throw new ConfigureException(__d('cake_dev', 'Unknown email configuration "%s".', $config));
  580. }
  581. $config = $configs->{$config};
  582. }
  583. $this->_config += $config;
  584. if (!empty($config['charset'])) {
  585. $this->charset = $config['charset'];
  586. }
  587. if (!empty($config['headerCharset'])) {
  588. $this->headerCharset = $config['headerCharset'];
  589. }
  590. if (empty($this->headerCharset)) {
  591. $this->headerCharset = $this->charset;
  592. }
  593. $simpleMethods = array(
  594. 'from', 'sender', 'to', 'replyTo', 'readReceipt', 'returnPath', 'cc', 'bcc',
  595. 'messageId', 'domain', 'subject', 'viewRender', 'viewVars', 'attachments',
  596. 'transport', 'emailFormat'
  597. );
  598. foreach ($simpleMethods as $method) {
  599. if (isset($config[$method])) {
  600. $this->$method($config[$method]);
  601. unset($config[$method]);
  602. }
  603. }
  604. if (isset($config['headers'])) {
  605. $this->setHeaders($config['headers']);
  606. unset($config['headers']);
  607. }
  608. if (array_key_exists('template', $config)) {
  609. $layout = false;
  610. if (array_key_exists('layout', $config)) {
  611. $layout = $config['layout'];
  612. unset($config['layout']);
  613. }
  614. $this->template($config['template'], $layout);
  615. unset($config['template']);
  616. }
  617. $this->transportClass()->config($config);
  618. }
  619. /**
  620. * Set the body of the mail as we send it.
  621. * Note: the text can be an array, each element will appear as a seperate line in the message body.
  622. *
  623. * LEAVE empty if you use $this->set() in combination with templates
  624. *
  625. * @param string/array: message
  626. * @return bool $success
  627. */
  628. public function send($message = null) {
  629. $this->_log = array(
  630. 'to' => $this->_to,
  631. 'from' => $this->_from,
  632. 'sender' => $this->_sender,
  633. 'replyTo' => $this->_replyTo,
  634. 'cc' => $this->_cc,
  635. 'subject' => $this->_subject,
  636. 'cc' => $this->_cc,
  637. 'transport' => $this->_transportName
  638. );
  639. # prep images for inline
  640. /*
  641. if ($this->_emailFormat !== 'text') {
  642. if ($message !== null) {
  643. $message = $this->_prepMessage($message);
  644. } else {
  645. $this->_htmlMessage = $this->_prepMessage($this->_htmlMessage);
  646. }
  647. }
  648. */
  649. try {
  650. $this->_debug = parent::send($message);
  651. } catch (Exception $e) {
  652. $this->_error = $e->getMessage();
  653. $this->_error .= ' (line '.$e->getLine().' in '.$e->getFile().')'.PHP_EOL.$e->getTraceAsString();
  654. if (!empty($this->_config['report'])) {
  655. $this->_logEmail();
  656. }
  657. return false;
  658. }
  659. if (!empty($this->_config['report'])) {
  660. $this->_logEmail();
  661. }
  662. return true;
  663. }
  664. protected function _prepMessage($text) {
  665. return $text;
  666. }
  667. /**
  668. * Returns the error if existent
  669. *
  670. * @return string
  671. */
  672. public function getError() {
  673. return $this->_error;
  674. }
  675. /**
  676. * Returns the debug content returned by send()
  677. *
  678. * @return string
  679. */
  680. public function getDebug() {
  681. return $this->_debug;
  682. }
  683. /**
  684. * Logs Email to type email
  685. * @return void
  686. */
  687. protected function _logEmail($append = null) {
  688. $res = $this->_log['transport'].
  689. ' - '.'TO:'.implode(',', array_keys($this->_log['to'])).
  690. '||FROM:'.implode(',', array_keys($this->_log['from'])).
  691. '||REPLY:'.implode(',', array_keys($this->_log['replyTo'])).
  692. '||S:'.$this->_log['subject'];
  693. $type = 'email';
  694. if (!empty($this->_error)) {
  695. $type = 'email_error';
  696. $res .= '||ERROR:' . $this->_error;
  697. }
  698. if ($append) {
  699. $res .= '||'.$append;
  700. }
  701. CakeLog::write($type, $res);
  702. }
  703. public function resetAndSet() {
  704. //$this->reset();
  705. $this->_to = array();
  706. $this->_cc = array();
  707. $this->_bcc = array();
  708. $this->_messageId = true;
  709. $this->_subject = '';
  710. $this->_headers = array();
  711. $this->_viewVars = array();
  712. $this->_textMessage = '';
  713. $this->_htmlMessage = '';
  714. $this->_message = '';
  715. $this->_attachments = array();
  716. $this->_error = null;
  717. $this->_debug = null;
  718. $this->from(Configure::read('Config.admin_email'), Configure::read('Config.admin_emailname'));
  719. if ($xMailer = Configure::read('Config.x-mailer')) {
  720. $this->addHeaders(array('X-Mailer'=>$xMailer));
  721. }
  722. //$this->_errors = array();
  723. //$this->charset($this->charset);
  724. //$this->sendAs($this->sendAs);
  725. //$this->layout($this->_layout);
  726. //$this->delivery($this->deliveryMethod);
  727. }
  728. }