Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

BaseMailer.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\mail;
  8. use Yii;
  9. use yii\base\Component;
  10. use yii\base\InvalidConfigException;
  11. use yii\base\ViewContextInterface;
  12. use yii\web\View;
  13. /**
  14. * BaseMailer serves as a base class that implements the basic functions required by [[MailerInterface]].
  15. *
  16. * Concrete child classes should may focus on implementing the [[sendMessage()]] method.
  17. *
  18. * @see BaseMessage
  19. *
  20. * @property View $view View instance. Note that the type of this property differs in getter and setter. See
  21. * [[getView()]] and [[setView()]] for details.
  22. * @property string $viewPath The directory that contains the view files for composing mail messages Defaults
  23. * to '@app/mail'.
  24. *
  25. * @author Paul Klimov <klimov.paul@gmail.com>
  26. * @since 2.0
  27. */
  28. abstract class BaseMailer extends Component implements MailerInterface, ViewContextInterface
  29. {
  30. /**
  31. * @event MailEvent an event raised right before send.
  32. * You may set [[MailEvent::isValid]] to be false to cancel the send.
  33. */
  34. const EVENT_BEFORE_SEND = 'beforeSend';
  35. /**
  36. * @event MailEvent an event raised right after send.
  37. */
  38. const EVENT_AFTER_SEND = 'afterSend';
  39. /**
  40. * @var string|boolean HTML layout view name. This is the layout used to render HTML mail body.
  41. * The property can take the following values:
  42. *
  43. * - a relative view name: a view file relative to [[viewPath]], e.g., 'layouts/html'.
  44. * - a path alias: an absolute view file path specified as a path alias, e.g., '@app/mail/html'.
  45. * - a boolean false: the layout is disabled.
  46. */
  47. public $htmlLayout = 'layouts/html';
  48. /**
  49. * @var string|boolean text layout view name. This is the layout used to render TEXT mail body.
  50. * Please refer to [[htmlLayout]] for possible values that this property can take.
  51. */
  52. public $textLayout = 'layouts/text';
  53. /**
  54. * @var array the configuration that should be applied to any newly created
  55. * email message instance by [[createMessage()]] or [[compose()]]. Any valid property defined
  56. * by [[MessageInterface]] can be configured, such as `from`, `to`, `subject`, `textBody`, `htmlBody`, etc.
  57. *
  58. * For example:
  59. *
  60. * ```php
  61. * [
  62. * 'charset' => 'UTF-8',
  63. * 'from' => 'noreply@mydomain.com',
  64. * 'bcc' => 'developer@mydomain.com',
  65. * ]
  66. * ```
  67. */
  68. public $messageConfig = [];
  69. /**
  70. * @var string the default class name of the new message instances created by [[createMessage()]]
  71. */
  72. public $messageClass = 'yii\mail\BaseMessage';
  73. /**
  74. * @var boolean whether to save email messages as files under [[fileTransportPath]] instead of sending them
  75. * to the actual recipients. This is usually used during development for debugging purpose.
  76. * @see fileTransportPath
  77. */
  78. public $useFileTransport = false;
  79. /**
  80. * @var string the directory where the email messages are saved when [[useFileTransport]] is true.
  81. */
  82. public $fileTransportPath = '@runtime/mail';
  83. /**
  84. * @var callable a PHP callback that will be called by [[send()]] when [[useFileTransport]] is true.
  85. * The callback should return a file name which will be used to save the email message.
  86. * If not set, the file name will be generated based on the current timestamp.
  87. *
  88. * The signature of the callback is:
  89. *
  90. * ```php
  91. * function ($mailer, $message)
  92. * ```
  93. */
  94. public $fileTransportCallback;
  95. /**
  96. * @var \yii\base\View|array view instance or its array configuration.
  97. */
  98. private $_view = [];
  99. /**
  100. * @var string the directory containing view files for composing mail messages.
  101. */
  102. private $_viewPath;
  103. /**
  104. * @param array|View $view view instance or its array configuration that will be used to
  105. * render message bodies.
  106. * @throws InvalidConfigException on invalid argument.
  107. */
  108. public function setView($view)
  109. {
  110. if (!is_array($view) && !is_object($view)) {
  111. throw new InvalidConfigException('"' . get_class($this) . '::view" should be either object or configuration array, "' . gettype($view) . '" given.');
  112. }
  113. $this->_view = $view;
  114. }
  115. /**
  116. * @return View view instance.
  117. */
  118. public function getView()
  119. {
  120. if (!is_object($this->_view)) {
  121. $this->_view = $this->createView($this->_view);
  122. }
  123. return $this->_view;
  124. }
  125. /**
  126. * Creates view instance from given configuration.
  127. * @param array $config view configuration.
  128. * @return View view instance.
  129. */
  130. protected function createView(array $config)
  131. {
  132. if (!array_key_exists('class', $config)) {
  133. $config['class'] = View::className();
  134. }
  135. return Yii::createObject($config);
  136. }
  137. private $_message;
  138. /**
  139. * Creates a new message instance and optionally composes its body content via view rendering.
  140. *
  141. * @param string|array|null $view the view to be used for rendering the message body. This can be:
  142. *
  143. * - a string, which represents the view name or path alias for rendering the HTML body of the email.
  144. * In this case, the text body will be generated by applying `strip_tags()` to the HTML body.
  145. * - an array with 'html' and/or 'text' elements. The 'html' element refers to the view name or path alias
  146. * for rendering the HTML body, while 'text' element is for rendering the text body. For example,
  147. * `['html' => 'contact-html', 'text' => 'contact-text']`.
  148. * - null, meaning the message instance will be returned without body content.
  149. *
  150. * The view to be rendered can be specified in one of the following formats:
  151. *
  152. * - path alias (e.g. "@app/mail/contact");
  153. * - a relative view name (e.g. "contact") located under [[viewPath]].
  154. *
  155. * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
  156. * @return MessageInterface message instance.
  157. */
  158. public function compose($view = null, array $params = [])
  159. {
  160. $message = $this->createMessage();
  161. if ($view === null) {
  162. return $message;
  163. }
  164. if (!array_key_exists('message', $params)) {
  165. $params['message'] = $message;
  166. }
  167. $this->_message = $message;
  168. if (is_array($view)) {
  169. if (isset($view['html'])) {
  170. $html = $this->render($view['html'], $params, $this->htmlLayout);
  171. }
  172. if (isset($view['text'])) {
  173. $text = $this->render($view['text'], $params, $this->textLayout);
  174. }
  175. } else {
  176. $html = $this->render($view, $params, $this->htmlLayout);
  177. }
  178. $this->_message = null;
  179. if (isset($html)) {
  180. $message->setHtmlBody($html);
  181. }
  182. if (isset($text)) {
  183. $message->setTextBody($text);
  184. } elseif (isset($html)) {
  185. if (preg_match('~<body[^>]*>(.*?)</body>~is', $html, $match)) {
  186. $html = $match[1];
  187. }
  188. // remove style and script
  189. $html = preg_replace('~<((style|script))[^>]*>(.*?)</\1>~is', '', $html);
  190. // strip all HTML tags and decoded HTML entities
  191. $text = html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, Yii::$app ? Yii::$app->charset : 'UTF-8');
  192. // improve whitespace
  193. $text = preg_replace("~^[ \t]+~m", '', trim($text));
  194. $text = preg_replace('~\R\R+~mu', "\n\n", $text);
  195. $message->setTextBody($text);
  196. }
  197. return $message;
  198. }
  199. /**
  200. * Creates a new message instance.
  201. * The newly created instance will be initialized with the configuration specified by [[messageConfig]].
  202. * If the configuration does not specify a 'class', the [[messageClass]] will be used as the class
  203. * of the new message instance.
  204. * @return MessageInterface message instance.
  205. */
  206. protected function createMessage()
  207. {
  208. $config = $this->messageConfig;
  209. if (!array_key_exists('class', $config)) {
  210. $config['class'] = $this->messageClass;
  211. }
  212. $config['mailer'] = $this;
  213. return Yii::createObject($config);
  214. }
  215. /**
  216. * Sends the given email message.
  217. * This method will log a message about the email being sent.
  218. * If [[useFileTransport]] is true, it will save the email as a file under [[fileTransportPath]].
  219. * Otherwise, it will call [[sendMessage()]] to send the email to its recipient(s).
  220. * Child classes should implement [[sendMessage()]] with the actual email sending logic.
  221. * @param MessageInterface $message email message instance to be sent
  222. * @return boolean whether the message has been sent successfully
  223. */
  224. public function send($message)
  225. {
  226. if (!$this->beforeSend($message)) {
  227. return false;
  228. }
  229. $address = $message->getTo();
  230. if (is_array($address)) {
  231. $address = implode(', ', array_keys($address));
  232. }
  233. Yii::info('Sending email "' . $message->getSubject() . '" to "' . $address . '"', __METHOD__);
  234. if ($this->useFileTransport) {
  235. $isSuccessful = $this->saveMessage($message);
  236. } else {
  237. $isSuccessful = $this->sendMessage($message);
  238. }
  239. $this->afterSend($message, $isSuccessful);
  240. return $isSuccessful;
  241. }
  242. /**
  243. * Sends multiple messages at once.
  244. *
  245. * The default implementation simply calls [[send()]] multiple times.
  246. * Child classes may override this method to implement more efficient way of
  247. * sending multiple messages.
  248. *
  249. * @param array $messages list of email messages, which should be sent.
  250. * @return integer number of messages that are successfully sent.
  251. */
  252. public function sendMultiple(array $messages)
  253. {
  254. $successCount = 0;
  255. foreach ($messages as $message) {
  256. if ($this->send($message)) {
  257. $successCount++;
  258. }
  259. }
  260. return $successCount;
  261. }
  262. /**
  263. * Renders the specified view with optional parameters and layout.
  264. * The view will be rendered using the [[view]] component.
  265. * @param string $view the view name or the path alias of the view file.
  266. * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
  267. * @param string|boolean $layout layout view name or path alias. If false, no layout will be applied.
  268. * @return string the rendering result.
  269. */
  270. public function render($view, $params = [], $layout = false)
  271. {
  272. $output = $this->getView()->render($view, $params, $this);
  273. if ($layout !== false) {
  274. return $this->getView()->render($layout, ['content' => $output, 'message' => $this->_message], $this);
  275. } else {
  276. return $output;
  277. }
  278. }
  279. /**
  280. * Sends the specified message.
  281. * This method should be implemented by child classes with the actual email sending logic.
  282. * @param MessageInterface $message the message to be sent
  283. * @return boolean whether the message is sent successfully
  284. */
  285. abstract protected function sendMessage($message);
  286. /**
  287. * Saves the message as a file under [[fileTransportPath]].
  288. * @param MessageInterface $message
  289. * @return boolean whether the message is saved successfully
  290. */
  291. protected function saveMessage($message)
  292. {
  293. $path = Yii::getAlias($this->fileTransportPath);
  294. if (!is_dir($path)) {
  295. mkdir($path, 0777, true);
  296. }
  297. if ($this->fileTransportCallback !== null) {
  298. $file = $path . '/' . call_user_func($this->fileTransportCallback, $this, $message);
  299. } else {
  300. $file = $path . '/' . $this->generateMessageFileName();
  301. }
  302. file_put_contents($file, $message->toString());
  303. return true;
  304. }
  305. /**
  306. * @return string the file name for saving the message when [[useFileTransport]] is true.
  307. */
  308. public function generateMessageFileName()
  309. {
  310. $time = microtime(true);
  311. return date('Ymd-His-', $time) . sprintf('%04d', (int) (($time - (int) $time) * 10000)) . '-' . sprintf('%04d', mt_rand(0, 10000)) . '.eml';
  312. }
  313. /**
  314. * @return string the directory that contains the view files for composing mail messages
  315. * Defaults to '@app/mail'.
  316. */
  317. public function getViewPath()
  318. {
  319. if ($this->_viewPath === null) {
  320. $this->setViewPath('@app/mail');
  321. }
  322. return $this->_viewPath;
  323. }
  324. /**
  325. * @param string $path the directory that contains the view files for composing mail messages
  326. * This can be specified as an absolute path or a path alias.
  327. */
  328. public function setViewPath($path)
  329. {
  330. $this->_viewPath = Yii::getAlias($path);
  331. }
  332. /**
  333. * This method is invoked right before mail send.
  334. * You may override this method to do last-minute preparation for the message.
  335. * If you override this method, please make sure you call the parent implementation first.
  336. * @param MessageInterface $message
  337. * @return boolean whether to continue sending an email.
  338. */
  339. public function beforeSend($message)
  340. {
  341. $event = new MailEvent(['message' => $message]);
  342. $this->trigger(self::EVENT_BEFORE_SEND, $event);
  343. return $event->isValid;
  344. }
  345. /**
  346. * This method is invoked right after mail was send.
  347. * You may override this method to do some postprocessing or logging based on mail send status.
  348. * If you override this method, please make sure you call the parent implementation first.
  349. * @param MessageInterface $message
  350. * @param boolean $isSuccessful
  351. */
  352. public function afterSend($message, $isSuccessful)
  353. {
  354. $event = new MailEvent(['message' => $message, 'isSuccessful' => $isSuccessful]);
  355. $this->trigger(self::EVENT_AFTER_SEND, $event);
  356. }
  357. }