EmailLib.php 25 KB

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